Start independent Ziran Daochi client

This commit is contained in:
waozi committed 2026-09-26 18:35:34 -03:00
commit 0063eda28c
12 files changed
+1172

No files matched your search

+13
View File
@@ -0,0 +1,13 @@
# Daochi Client repository rules
- This repository owns reusable Daochi client protocol and request behavior.
The Daochi Go server and mesh node stay in `daochi`; app storage, merge rules,
and UI stay in each app; widgets stay in Kryon.
- Production implementation is Ziran `.zi`. C is allowed only in test harnesses
and generated output. Do not add compatibility wrappers for old Kryon sync.
- Use direct API names such as `Client`, `Session`, `Login`, and `BearerRequest`.
- Preserve released wire formats and result codes. Test against Daochi server
fixtures when changing signed messages or protocol versions.
- Do not persist or log private keys or bearer tokens in this library. The app
supplies key storage and token persistence.
- Run `sh tests/run.sh` and `git diff --check` before committing.
+3
View File
@@ -0,0 +1,3 @@
.PHONY: test
test:
sh tests/run.sh
+29
View File
@@ -0,0 +1,29 @@
# Daochi Client
Daochi Client is the independent Ziran library for applications that sync with
Daochi. It contains no server, mesh node, database, or UI implementation.
The portable modules currently provide:
- canonical challenge, login body, and signed message builders (`wire.zi`);
- HTTPS and local network URL policy (`url.zi`);
- challenge parsing, signed login preparation, and token parsing (`auth.zi`);
- login and bearer requests with one fresh login after a `401` (`client.zi`).
The application supplies the account signer and body digest. A host supplies
bounded HTTP requests through `SendRequest`; the host must NUL terminate every
response buffer, including on error. This keeps private keys in the app's key
store and keeps platform transport outside the protocol core. Applications
persist `Session` if they want bearer tokens to survive restart. Account keys
must remain when a bearer token expires.
Add this repository and Ziran's `std` directory to the Ziran module paths, then
import `client`. For an Inbe native host, adapt `SendRequest` to Ziran's curl
module. Browser and Android hosts can implement the same request boundary.
`sh tests/run.sh` checks the library using the sibling `ziran` checkout. Set
`ZIRAN_DIR` when that checkout is elsewhere.
The client migration is in progress. Full payload sync, protocol v6 signed
transactions, social actions, device registration, and remote events are not
yet implemented in this repository.
+166
View File
@@ -0,0 +1,166 @@
// Portable challenge/login protocol. The application owns keys and the host
// owns HTTP; neither is stored here.
#import "wire"
#import "json_scan"
#import "byte_text_linux"
AuthResult :: enum {
AUTH_OK :: 0
AUTH_INVALID_URL :: 1
AUTH_NO_ACCOUNT :: 2
AUTH_PAYLOAD_FAILED :: 3
AUTH_CHALLENGE_FAILED :: 4
AUTH_SIGN_FAILED :: 5
AUTH_REQUEST_FAILED :: 6
AUTH_FAILED :: 7
}
using AuthResult;
Identity :: struct {
account_id: string
public_key: string
client_id: string
signing_context: *void
}
Session :: struct {
token: [4096]u8
expires_in_seconds: s64
server_time: s64
expires_at_local: s64
}
DigestBody :: #type (body: string, output: []u8) -> bool #c_call;
SignMessage :: #type (context: *void, message: string,
output: []u8) -> bool #c_call;
ValidJson :: (json: string) -> bool {
end := ValueEnd(json, 0, 0)
return end >= 0 && Space(json, end) == cast(s32)json.count
}
FieldText :: (json: string, name: string, output: []u8) -> bool {
if output.count == 0 || !ValidJson(json) {
return false
}
output[0] = cast(u8)0
at := FieldAt(json, 0, name)
span := ReadString(json, at)
if !span.valid || span.end <= span.start ||
cast(s64)(span.end - span.start) >= output.count {
return false
}
index: s32 = 0
while index < span.end - span.start {
byte := json[span.start + index]
if byte < cast(u8)33 || byte >= cast(u8)127 ||
byte == cast(u8)92 {
return false
}
output[index] = byte
index += 1
}
output[index] = cast(u8)0
return true
}
FieldNumber :: (json: string, name: string, fallback: s64) -> s64 {
at := FieldAt(json, 0, name)
number := ReadNumber(json, at)
if !number.valid || number.value < 0 ||
number.value > 9007199254740991.0 {
return fallback
}
return cast(s64)number.value
}
HexText :: (text: string, digits: s64) -> bool {
if cast(s64)text.count != digits {
return false
}
index: s64 = 0
while index < digits {
byte := text[index]
if !((byte >= cast(u8)48 && byte <= cast(u8)57) ||
(byte >= cast(u8)65 && byte <= cast(u8)70) ||
(byte >= cast(u8)97 && byte <= cast(u8)102)) {
return false
}
index += 1
}
return true
}
#scope_export
#program_export
PrepareLogin :: (identity: Identity, challenge_json: string,
digest: DigestBody, signer: SignMessage,
body: []u8, signature: []u8) -> AuthResult {
if body.count > 0 {
body[0] = cast(u8)0
}
if signature.count > 0 {
signature[0] = cast(u8)0
}
if !HexText(identity.account_id, 64) ||
identity.public_key.count == 0 {
return cast(AuthResult)AUTH_NO_ACCOUNT
}
if identity.client_id.count == 0 || body.count == 0 ||
signature.count < 4841 {
return cast(AuthResult)AUTH_PAYLOAD_FAILED
}
nonce: [65]u8
if !FieldText(challenge_json, "nonce", nonce[:]) ||
!HexText(TextFromCString(*nonce[0]), 64) {
return cast(AuthResult)AUTH_CHALLENGE_FAILED
}
if !BuildLoginBody(identity.account_id, identity.client_id,
identity.public_key, body) {
return cast(AuthResult)AUTH_PAYLOAD_FAILED
}
body_hash: [65]u8
body_hash[0] = cast(u8)0
if !digest(TextFromCString(*body[0]), body_hash[:]) ||
!HexText(TextFromCString(*body_hash[0]), 64) {
return cast(AuthResult)AUTH_SIGN_FAILED
}
message: [256]u8
if !BuildLoginMessageHash(TextFromCString(*body_hash[0]),
TextFromCString(*nonce[0]), message[:]) {
return cast(AuthResult)AUTH_SIGN_FAILED
}
if !signer(identity.signing_context,
TextFromCString(*message[0]), signature) ||
!HexText(TextFromCString(*signature[0]), 4840) {
signature[0] = cast(u8)0
return cast(AuthResult)AUTH_SIGN_FAILED
}
return cast(AuthResult)AUTH_OK
}
#scope_export
#program_export
AcceptLogin :: (status: s32, response_json: string,
session: *Session) -> AuthResult {
if session == null {
return cast(AuthResult)AUTH_PAYLOAD_FAILED
}
session.* = Session.{}
if status == 401 {
return cast(AuthResult)AUTH_FAILED
}
if status < 200 || status >= 300 {
return cast(AuthResult)AUTH_REQUEST_FAILED
}
if !FieldText(response_json, "auth_token", session.token[:]) {
return cast(AuthResult)AUTH_PAYLOAD_FAILED
}
session.expires_in_seconds = FieldNumber(response_json,
"expires_in_seconds", 3600)
session.server_time = FieldNumber(response_json, "server_time", 0)
return cast(AuthResult)AUTH_OK
}
+214
View File
@@ -0,0 +1,214 @@
// Synchronous Daochi client entry points. Hosts provide the bounded request
// callback, so this module contains no platform or application implementation.
#import "auth"
#import "url"
#import "wire"
#import "net_http"
#import "byte_text_linux"
SendRequest :: #type (context: *void, request: HttpRequest,
output: []u8, status: *s32) -> bool #c_call;
Client :: struct {
server_url: string
identity: Identity
digest: DigestBody
signer: SignMessage
send: SendRequest
transport_context: *void
}
#scope_export
#program_export
Login :: (client: Client, session: *Session) -> AuthResult {
if session == null {
return cast(AuthResult)AuthResult.AUTH_PAYLOAD_FAILED
}
session.* = Session.{}
server: [512]u8
if !NormalizeUrl(client.server_url, server[:]) {
return cast(AuthResult)AuthResult.AUTH_INVALID_URL
}
path: [128]u8
if !BuildChallengePath(client.identity.account_id, path[:]) {
return cast(AuthResult)AuthResult.AUTH_NO_ACCOUNT
}
url: [768]u8
if !JoinUrl(TextFromCString(*server[0]),
TextFromCString(*path[0]), url[:]) {
return cast(AuthResult)AuthResult.AUTH_INVALID_URL
}
request: HttpRequest
request.method = "GET"
request.url = TextFromCString(*url[0])
request.accept = "application/json"
challenge: [4096]u8
status: s32 = 0
if !client.send(client.transport_context, request,
challenge[:], *status) || status != 200 {
if status == 401 {
return cast(AuthResult)AuthResult.AUTH_FAILED
}
return cast(AuthResult)AuthResult.AUTH_CHALLENGE_FAILED
}
body: [4096]u8
signature: [4841]u8
prepared := PrepareLogin(client.identity,
TextFromCString(*challenge[0]), client.digest, client.signer,
body[:], signature[:])
if prepared != cast(AuthResult)AuthResult.AUTH_OK {
return prepared
}
if !JoinUrl(TextFromCString(*server[0]),
"/api/v1/sync/login", url[:]) {
return cast(AuthResult)AuthResult.AUTH_INVALID_URL
}
headers: [2]HttpHeader
headers[0].name = "X-Daochi-User"
headers[0].value = client.identity.account_id
headers[1].name = "X-Daochi-Signature"
headers[1].value = TextFromCString(*signature[0])
request.method = "POST"
request.url = TextFromCString(*url[0])
request.content_type = "application/json"
request.body = TextFromCString(*body[0])
request.headers = headers[:]
response: [8192]u8
status = 0
if !client.send(client.transport_context, request,
response[:], *status) {
return cast(AuthResult)AuthResult.AUTH_REQUEST_FAILED
}
return AcceptLogin(status, TextFromCString(*response[0]), session)
}
MethodValid :: (method: string) -> bool {
if method.count == 0 || method.count >= 32 {
return false
}
index: s64 = 0
while index < cast(s64)method.count {
byte := method[index]
if !((byte >= cast(u8)65 && byte <= cast(u8)90) ||
(byte >= cast(u8)97 && byte <= cast(u8)122) ||
byte == cast(u8)45) {
return false
}
index += 1
}
return true
}
PathValid :: (path: string) -> bool {
if path.count == 0 || path[0] != cast(u8)47 {
return false
}
index: s64 = 0
while index < cast(s64)path.count {
byte := path[index]
if byte <= cast(u8)32 || byte >= cast(u8)127 ||
byte == cast(u8)35 {
return false
}
index += 1
}
return true
}
TokenValid :: (session: *Session, now: s64) -> bool {
return session.token[0] != cast(u8)0 &&
session.expires_at_local > now
}
SetExpiry :: (session: *Session, now: s64) {
session.expires_at_local = now
if now < 0 || session.expires_in_seconds <= 30 ||
session.expires_in_seconds > 9007199254740991 - now {
return
}
session.expires_at_local = now + session.expires_in_seconds - 30
}
#scope_export
#program_export
ClearSession :: (session: *Session) {
if session != null {
session.* = Session.{}
}
}
// A 401 invalidates the bearer token, then performs exactly one fresh login
// and retries the original request. The caller persists the resulting session.
#scope_export
#program_export
BearerRequest :: (client: Client, session: *Session, now: s64,
method: string, path: string, body: string, output: []u8,
status: *s32) -> AuthResult {
if output.count == 0 || session == null || status == null {
return cast(AuthResult)AuthResult.AUTH_PAYLOAD_FAILED
}
output[0] = cast(u8)0
status.* = 0
if !MethodValid(method) || !PathValid(path) {
return cast(AuthResult)AuthResult.AUTH_PAYLOAD_FAILED
}
server: [512]u8
if !NormalizeUrl(client.server_url, server[:]) {
return cast(AuthResult)AuthResult.AUTH_INVALID_URL
}
url: [2048]u8
if !JoinUrl(TextFromCString(*server[0]), path, url[:]) {
return cast(AuthResult)AuthResult.AUTH_INVALID_URL
}
if !TokenValid(session, now) {
login_result := Login(client, session)
if login_result != cast(AuthResult)AuthResult.AUTH_OK {
return login_result
}
SetExpiry(session, now)
}
attempt: s32 = 0
while attempt < 2 {
headers: [2]HttpHeader
headers[0].name = "X-Daochi-User"
headers[0].value = client.identity.account_id
headers[1].name = "X-Daochi-Client"
headers[1].value = client.identity.client_id
request: HttpRequest
request.method = method
request.url = TextFromCString(*url[0])
request.token = TextFromCString(*session.token[0])
request.accept = "application/json"
request.headers = headers[:]
if body.count > 0 {
request.body = body
request.content_type = "application/json"
}
output[0] = cast(u8)0
status.* = 0
if !client.send(client.transport_context, request,
output, status) {
return cast(AuthResult)AuthResult.AUTH_REQUEST_FAILED
}
if status.* >= 200 && status.* < 300 {
return cast(AuthResult)AuthResult.AUTH_OK
}
if status.* != 401 {
return cast(AuthResult)AuthResult.AUTH_REQUEST_FAILED
}
ClearSession(session)
if attempt == 1 {
return cast(AuthResult)AuthResult.AUTH_FAILED
}
login_result := Login(client, session)
if login_result != cast(AuthResult)AuthResult.AUTH_OK {
return login_result
}
SetExpiry(session, now)
attempt += 1
}
return cast(AuthResult)AuthResult.AUTH_FAILED
}
+83
View File
@@ -0,0 +1,83 @@
#include "auth.h"
#include <assert.h>
#include <stdio.h>
#include <string.h>
static bool digest(String body, Slice output)
{
const char *prefix = "{\"user_id_hash\":\"";
assert(body.length > strlen(prefix));
assert(memcmp(body.data, prefix, strlen(prefix)) == 0);
assert(output.length >= 65);
memset(output.data, 'b', 64);
((char *)output.data)[64] = 0;
return true;
}
static bool sign_message(void *context, String message, Slice output)
{
assert(context == (void *)0x1);
const char prefix[] = "daochi-sync-v1\nPOST\n/api/v1/sync/login\n";
size_t head = sizeof prefix - 1;
assert(message.length == head + 64 + 1 + 64 + 1);
assert(memcmp(message.data, prefix, head) == 0);
for (size_t index = 0; index < 64; ++index) {
assert(message.data[head + index] == 'b');
assert(message.data[head + 65 + index] == 'c');
}
assert(message.data[head + 64] == '\n');
assert(message.data[head + 129] == '\n');
assert(output.length >= 4841);
memset(output.data, 'd', 4840);
((char *)output.data)[4840] = 0;
return true;
}
int main(void)
{
char account_id[65];
char body[4096];
char signature[4841];
memset(account_id, 'a', 64);
account_id[64] = 0;
Identity identity = {
.account_id = StringView(account_id, 64),
.public_key = StringLiteral("public-key"),
.client_id = StringLiteral("client-1"),
.signing_context = (void *)0x1,
};
Slice body_buffer = {.data = body, .length = sizeof body};
Slice signature_buffer = {.data = signature, .length = sizeof signature};
char challenge[80];
snprintf(challenge, sizeof challenge, "{\"nonce\":\"%064d\"}", 0);
memset(challenge + 10, 'c', 64);
AuthResult result = PrepareLogin(identity,
StringView(challenge, strlen(challenge)), digest, sign_message,
body_buffer, signature_buffer);
assert(result == AuthResult_AUTH_OK);
assert(strstr(body, "\"client_id\":\"client-1\"") != NULL);
assert(strlen(signature) == 4840);
result = PrepareLogin(identity, StringLiteral("{\"nonce\":\"short\"}"),
digest, sign_message, body_buffer, signature_buffer);
assert(result == AuthResult_AUTH_CHALLENGE_FAILED);
assert(body[0] == 0 && signature[0] == 0);
Session session = {0};
result = AcceptLogin(200, StringLiteral(
"{\"auth_token\":\"token\",\"expires_in_seconds\":1800,"
"\"server_time\":1700000000}"), &session);
assert(result == AuthResult_AUTH_OK);
assert(strcmp((char *)session.token, "token") == 0);
assert(session.expires_in_seconds == 1800);
assert(session.server_time == 1700000000);
result = AcceptLogin(401, StringLiteral("{}"), &session);
assert(result == AuthResult_AUTH_FAILED);
assert(session.token[0] == 0);
result = AcceptLogin(200, StringLiteral("{}"), &session);
assert(result == AuthResult_AUTH_PAYLOAD_FAILED);
puts("Daochi Ziran login protocol passed");
return 0;
}
+185
View File
@@ -0,0 +1,185 @@
#include "client.h"
#include <assert.h>
#include <stdio.h>
#include <string.h>
typedef struct FakeServer {
int calls;
int login_status;
int challenge_calls;
int login_calls;
int sync_calls;
bool reject_sync_once;
} FakeServer;
static bool digest(String body, Slice output)
{
assert(body.length > 100);
assert(output.length >= 65);
memset(output.data, 'b', 64);
((char *)output.data)[64] = 0;
return true;
}
static bool sign_message(void *context, String message, Slice output)
{
assert(context == (void *)0x1);
assert(message.length > 100);
assert(output.length >= 4841);
memset(output.data, 'd', 4840);
((char *)output.data)[4840] = 0;
return true;
}
static bool send_request(void *context, HttpRequest request,
Slice output, int32_t *status)
{
FakeServer *server = context;
++server->calls;
assert(output.length >= 256);
assert(request.accept.length == strlen("application/json"));
if (server->calls == 1) {
assert(request.method.length == 3);
assert(memcmp(request.method.data, "GET", 3) == 0);
const char *path = "/api/v1/sync/challenge?user_id=";
assert(strstr(request.url.data, path) != NULL);
char nonce[80];
snprintf(nonce, sizeof nonce, "{\"nonce\":\"%064d\"}", 0);
memset(nonce + 10, 'c', 64);
strcpy(output.data, nonce);
*status = 200;
return true;
}
assert(server->calls == 2);
assert(request.method.length == 4);
assert(memcmp(request.method.data, "POST", 4) == 0);
assert(strstr(request.url.data, "/api/v1/sync/login") != NULL);
assert(request.body.length > 100);
assert(request.headers.length == 2);
const HttpHeader *headers = request.headers.data;
assert(headers[0].name.length == strlen("X-Daochi-User"));
assert(headers[0].value.length == 64);
assert(headers[1].name.length == strlen("X-Daochi-Signature"));
assert(headers[1].value.length == 4840);
*status = server->login_status;
if (*status == 200) {
strcpy(output.data,
"{\"auth_token\":\"token\",\"expires_in_seconds\":1800,"
"\"server_time\":1700000000}");
} else {
strcpy(output.data, "{}");
}
return true;
}
static bool send_bearer(void *context, HttpRequest request,
Slice output, int32_t *status)
{
FakeServer *server = context;
if (request.method.length == 3 &&
memcmp(request.method.data, "GET", 3) == 0) {
++server->challenge_calls;
char nonce[80];
snprintf(nonce, sizeof nonce, "{\"nonce\":\"%064d\"}", 0);
memset(nonce + 10, 'c', 64);
strcpy(output.data, nonce);
*status = 200;
return true;
}
assert(request.method.length == 4);
assert(memcmp(request.method.data, "POST", 4) == 0);
if (strstr(request.url.data, "/api/v1/sync/login") != NULL) {
++server->login_calls;
strcpy(output.data,
"{\"auth_token\":\"token\",\"expires_in_seconds\":1800,"
"\"server_time\":1700000000}");
*status = 200;
return true;
}
assert(strstr(request.url.data, "/api/v1/sync") != NULL);
assert(request.token.length == 5);
assert(memcmp(request.token.data, "token", 5) == 0);
assert(request.headers.length == 2);
const HttpHeader *headers = request.headers.data;
assert(headers[0].value.length == 64);
assert(headers[1].value.length == strlen("client-1"));
assert(request.body.length == 2);
assert(memcmp(request.body.data, "{}", 2) == 0);
++server->sync_calls;
if (server->reject_sync_once) {
server->reject_sync_once = false;
strcpy(output.data, "{}");
*status = 401;
} else {
strcpy(output.data, "{\"server_version\":3}");
*status = 200;
}
return true;
}
int main(void)
{
char account_id[65];
memset(account_id, 'a', 64);
account_id[64] = 0;
FakeServer server = {.login_status = 200};
Client client = {0};
client.server_url = StringLiteral("http://127.0.0.1:8080");
client.identity.account_id = StringView(account_id, 64);
client.identity.public_key = StringLiteral("public-key");
client.identity.client_id = StringLiteral("client-1");
client.identity.signing_context = (void *)0x1;
client.digest = digest;
client.signer = sign_message;
client.send = send_request;
client.transport_context = &server;
Session session = {0};
AuthResult result = Login(client, &session);
assert(result == AuthResult_AUTH_OK);
assert(server.calls == 2);
assert(strcmp((char *)session.token, "token") == 0);
server.calls = 0;
server.login_status = 401;
result = Login(client, &session);
assert(result == AuthResult_AUTH_FAILED);
assert(session.token[0] == 0);
server.calls = 0;
client.server_url = StringLiteral("http://public.example.org");
result = Login(client, &session);
assert(result == AuthResult_AUTH_INVALID_URL);
assert(server.calls == 0);
memset(&server, 0, sizeof server);
client.server_url = StringLiteral("http://127.0.0.1:8080");
client.send = send_bearer;
session = (Session){0};
char output[256];
int32_t status = 0;
result = BearerRequest(client, &session, 1000, StringLiteral("POST"),
StringLiteral("/api/v1/sync"), StringLiteral("{}"),
(Slice){.data = output, .length = sizeof output}, &status);
assert(result == AuthResult_AUTH_OK && status == 200);
assert(server.challenge_calls == 1 && server.login_calls == 1);
assert(server.sync_calls == 1);
assert(session.expires_at_local == 2770);
assert(strcmp(output, "{\"server_version\":3}") == 0);
server.reject_sync_once = true;
result = BearerRequest(client, &session, 1001, StringLiteral("POST"),
StringLiteral("/api/v1/sync"), StringLiteral("{}"),
(Slice){.data = output, .length = sizeof output}, &status);
assert(result == AuthResult_AUTH_OK && status == 200);
assert(server.challenge_calls == 2 && server.login_calls == 2);
assert(server.sync_calls == 3);
result = BearerRequest(client, &session, 1002, StringLiteral("POST\r\n"),
StringLiteral("/api/v1/sync"), StringLiteral("{}"),
(Slice){.data = output, .length = sizeof output}, &status);
assert(result == AuthResult_AUTH_PAYLOAD_FAILED);
assert(server.sync_calls == 3);
puts("Daochi Ziran client login passed");
return 0;
}
+24
View File
@@ -0,0 +1,24 @@
#!/bin/sh
set -eu
root=$(CDPATH= cd -- "$(dirname -- "$0")/.." && pwd)
ziran=${ZIRAN_DIR:-"$root/../ziran"}
work=$(mktemp -d)
trap 'rm -rf "$work"' EXIT HUP INT TERM
"$ziran/build/bin/zi2c" --no-main --root "$root" \
--module-path "$ziran/std" -o "$work/generated" \
"$root/client.zi"
for test in wire auth url client; do
"${CC:-cc}" -std=c11 -O0 -Wall -Wextra -Werror \
-Wno-unused-function -Wno-unused-variable \
-I"$ziran/include" -I"$work/generated" \
"$root/tests/${test}_test.c" \
"$work/generated/auth.c" "$work/generated/client.c" \
"$work/generated/url.c" "$work/generated/wire.c" \
"$work/generated/json_scan.c" "$work/generated/byte_text_linux.c" \
"$work/generated/text.c" \
-o "$work/${test}_test"
env -u DISPLAY -u WAYLAND_DISPLAY "$work/${test}_test"
done
+32
View File
@@ -0,0 +1,32 @@
#include "url.h"
#include <assert.h>
#include <stdio.h>
#include <string.h>
int main(void)
{
char output[256];
Slice buffer = {.data = output, .length = sizeof output};
assert(UrlValid(StringLiteral("https://api.example.org")));
assert(UrlValid(StringLiteral("http://localhost:8080")));
assert(UrlValid(StringLiteral("127.0.0.1:8080")));
assert(UrlValid(StringLiteral("http://192.168.1.12")));
assert(!UrlValid(StringLiteral("http://api.example.org")));
assert(!UrlValid(StringLiteral("http://localhost.evil")));
assert(!UrlValid(StringLiteral("http://192.168.1.256")));
assert(!UrlValid(StringLiteral("https://api.example.org\r\n")));
assert(NormalizeUrl(StringLiteral("127.0.0.1:8080"), buffer));
assert(strcmp(output, "http://127.0.0.1:8080") == 0);
assert(JoinUrl(StringLiteral("https://api.example.org/"),
StringLiteral("/api/v1/sync"), buffer));
assert(strcmp(output, "https://api.example.org/api/v1/sync") == 0);
assert(JoinWebSocketUrl(StringLiteral("https://api.example.org"),
StringLiteral("/api/v1/sync/ws"), buffer));
assert(strcmp(output, "wss://api.example.org/api/v1/sync/ws") == 0);
buffer.length = 4;
assert(!NormalizeUrl(StringLiteral("localhost"), buffer));
assert(output[0] == 0);
puts("Daochi Ziran URL policy passed");
return 0;
}
+51
View File
@@ -0,0 +1,51 @@
#include "wire.h"
#include <assert.h>
#include <stdio.h>
#include <string.h>
int main(void)
{
char account_id[65];
char body_hash[65];
char nonce[65];
char output[512];
memset(account_id, 'a', 64);
memset(body_hash, 'b', 64);
memset(nonce, 'c', 64);
account_id[64] = 0;
body_hash[64] = 0;
nonce[64] = 0;
Slice buffer = {.data = output, .length = sizeof output};
assert(BuildChallengePath(StringView(account_id, 64), buffer));
assert(strcmp(output,
"/api/v1/sync/challenge?user_id=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa") == 0);
assert(BuildLoginBody(StringView(account_id, 64),
StringLiteral("client-1"), StringLiteral("key"), buffer));
assert(strcmp(output,
"{\"user_id_hash\":\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\",\"client_id\":\"client-1\","
"\"public_key\":\"key\"}") == 0);
assert(BuildLoginMessageHash(StringView(body_hash, 64),
StringView(nonce, 64), buffer));
assert(strcmp(output,
"daochi-sync-v1\nPOST\n/api/v1/sync/login\n"
"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb\n"
"cccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc\n") == 0);
assert(!BuildChallengePath(StringLiteral("invalid"), buffer));
assert(output[0] == 0);
assert(!BuildLoginMessageHash(StringLiteral("invalid"),
StringView(nonce, 64), buffer));
assert(output[0] == 0);
buffer.length = 8;
assert(!BuildLoginBody(StringView(account_id, 64),
StringLiteral("client-1"), StringLiteral("key"), buffer));
assert(output[0] == 0);
puts("Daochi Ziran wire contract passed");
return 0;
}
+197
View File
@@ -0,0 +1,197 @@
// Daochi server URLs use HTTPS except for loopback and private LAN hosts.
#import "byte_text_linux"
StartsWith :: (value: string, prefix: string) -> bool {
if value.count < prefix.count {
return false
}
index: s64 = 0
while index < cast(s64)prefix.count {
if value[index] != prefix[index] {
return false
}
index += 1
}
return true
}
HostBoundary :: (authority: string, index: s64) -> bool {
if index >= cast(s64)authority.count {
return true
}
byte := authority[index]
return byte == cast(u8)58 || byte == cast(u8)47 ||
byte == cast(u8)63 || byte == cast(u8)35
}
PrivateIpv4Authority :: (authority: string) -> bool {
octets: [4]s32
position: s64 = 0
part: s32 = 0
while part < 4 {
value: s32 = 0
digits: s32 = 0
while position < cast(s64)authority.count &&
authority[position] >= cast(u8)48 &&
authority[position] <= cast(u8)57 {
value = value * 10 + cast(s32)(authority[position] - cast(u8)48)
digits += 1
if value > 255 || digits > 3 {
return false
}
position += 1
}
if digits == 0 {
return false
}
octets[part] = value
if part < 3 {
if position >= cast(s64)authority.count ||
authority[position] != cast(u8)46 {
return false
}
position += 1
}
part += 1
}
if !HostBoundary(authority, position) {
return false
}
return octets[0] == 10 ||
(octets[0] == 172 && octets[1] >= 16 && octets[1] <= 31) ||
(octets[0] == 192 && octets[1] == 168) ||
(octets[0] == 169 && octets[1] == 254)
}
LocalAuthority :: (authority: string) -> bool {
if authority.count == 0 {
return false
}
if StartsWith(authority, "localhost") && HostBoundary(authority, 9) {
return true
}
if StartsWith(authority, "127.0.0.1") && HostBoundary(authority, 9) {
return true
}
if StartsWith(authority, "10.0.2.2") && HostBoundary(authority, 8) {
return true
}
return PrivateIpv4Authority(authority)
}
SafeUrlBytes :: (value: string) -> bool {
index: s64 = 0
while index < cast(s64)value.count {
byte := value[index]
if byte <= cast(u8)32 || byte >= cast(u8)127 {
return false
}
index += 1
}
return true
}
#scope_export
#program_export
UrlValid :: (url: string) -> bool {
if !SafeUrlBytes(url) {
return false
}
if StartsWith(url, "https://") {
return url.count > 8
}
if StartsWith(url, "http://") {
return LocalAuthority(url[7:])
}
return LocalAuthority(url)
}
#scope_export
#program_export
NormalizeUrl :: (input: string, output: []u8) -> bool {
if output.count == 0 {
return false
}
output[0] = cast(u8)0
if !UrlValid(input) {
return false
}
cursor: s64 = 0
if !StartsWith(input, "https://") &&
!StartsWith(input, "http://") {
if !WriteUrlText(output, *cursor, "http://") {
return false
}
}
if !WriteUrlText(output, *cursor, input) {
output[0] = cast(u8)0
return false
}
return true
}
WriteUrlText :: (output: []u8, cursor: *s64, value: string) -> bool {
if cursor.* < 0 || value.count >= output.count - cursor.* {
return false
}
index: s64 = 0
while index < cast(s64)value.count {
output[cursor.*] = value[index]
cursor.* += 1
index += 1
}
output[cursor.*] = cast(u8)0
return true
}
#scope_export
#program_export
JoinUrl :: (base_url: string, path: string, output: []u8) -> bool {
if output.count == 0 {
return false
}
output[0] = cast(u8)0
if path.count == 0 || path[0] != cast(u8)47 ||
!UrlValid(base_url) {
return false
}
end := cast(s64)base_url.count
while end > 0 && base_url[end - 1] == cast(u8)47 {
end -= 1
}
cursor: s64 = 0
if !WriteUrlText(output, *cursor, base_url[0:end]) ||
!WriteUrlText(output, *cursor, path) {
output[0] = cast(u8)0
return false
}
return true
}
#scope_export
#program_export
JoinWebSocketUrl :: (base_url: string, path: string,
output: []u8) -> bool {
if output.count == 0 {
return false
}
output[0] = cast(u8)0
http_url: [2048]u8
if !JoinUrl(base_url, path, http_url[:]) {
return false
}
url := TextFromCString(*http_url[0])
cursor: s64 = 0
complete := false
if StartsWith(url, "https://") {
complete = WriteUrlText(output, *cursor, "wss://") &&
WriteUrlText(output, *cursor, url[8:])
} else if StartsWith(url, "http://") {
complete = WriteUrlText(output, *cursor, "ws://") &&
WriteUrlText(output, *cursor, url[7:])
}
if !complete {
output[0] = cast(u8)0
}
return complete
}
+175
View File
@@ -0,0 +1,175 @@
// Daochi client wire values shared by apps. The caller owns account keys,
// hashing, HTTP transport, and the destination buffers.
WriteByte :: (output: []u8, cursor: *s64, byte: u8) -> bool {
if cursor.* < 0 || cursor.* + 1 >= output.count {
return false
}
output[cursor.*] = byte
cursor.* += 1
output[cursor.*] = cast(u8)0
return true
}
WriteText :: (output: []u8, cursor: *s64, value: string) -> bool {
if cursor.* < 0 || value.count >= output.count - cursor.* {
return false
}
index: s64 = 0
while index < cast(s64)value.count {
output[cursor.*] = value[index]
cursor.* += 1
index += 1
}
output[cursor.*] = cast(u8)0
return true
}
HexDigit :: (byte: u8) -> bool {
return (byte >= cast(u8)48 && byte <= cast(u8)57) ||
(byte >= cast(u8)65 && byte <= cast(u8)70) ||
(byte >= cast(u8)97 && byte <= cast(u8)102)
}
Hex64 :: (value: string) -> bool {
if value.count != 64 {
return false
}
index: s64 = 0
while index < 64 {
if !HexDigit(value[index]) {
return false
}
index += 1
}
return true
}
HexUpper :: (value: u8) -> u8 {
if value < 10 {
return cast(u8)48 + value
}
return cast(u8)65 + value - cast(u8)10
}
AppendJsonQuoted :: (output: []u8, cursor: *s64,
value: string) -> bool {
if !WriteByte(output, cursor, cast(u8)34) {
return false
}
index: s64 = 0
while index < cast(s64)value.count {
byte := value[index]
if byte == cast(u8)34 || byte == cast(u8)92 {
if !WriteByte(output, cursor, cast(u8)92) ||
!WriteByte(output, cursor, byte) {
return false
}
} else if byte == cast(u8)8 || byte == cast(u8)12 ||
byte == cast(u8)10 || byte == cast(u8)13 ||
byte == cast(u8)9 {
escape := cast(u8)98
if byte == cast(u8)12 {
escape = cast(u8)102
}
if byte == cast(u8)10 {
escape = cast(u8)110
}
if byte == cast(u8)13 {
escape = cast(u8)114
}
if byte == cast(u8)9 {
escape = cast(u8)116
}
if !WriteByte(output, cursor, cast(u8)92) ||
!WriteByte(output, cursor, escape) {
return false
}
} else if byte < cast(u8)32 {
if !WriteByte(output, cursor, cast(u8)92) ||
!WriteByte(output, cursor, cast(u8)117) ||
!WriteByte(output, cursor, cast(u8)48) ||
!WriteByte(output, cursor, cast(u8)48) ||
!WriteByte(output, cursor, HexUpper(byte / cast(u8)16)) ||
!WriteByte(output, cursor, HexUpper(byte % cast(u8)16)) {
return false
}
} else if !WriteByte(output, cursor, byte) {
return false
}
index += 1
}
return WriteByte(output, cursor, cast(u8)34)
}
#scope_export
#program_export
BuildChallengePath :: (account_id: string, output: []u8) -> bool {
if output.count == 0 {
return false
}
output[0] = cast(u8)0
if !Hex64(account_id) {
return false
}
cursor: s64 = 0
if !WriteText(output, *cursor,
"/api/v1/sync/challenge?user_id=") ||
!WriteText(output, *cursor, account_id) {
output[0] = cast(u8)0
return false
}
return true
}
#scope_export
#program_export
BuildLoginBody :: (account_id: string, client_id: string,
public_key: string, output: []u8) -> bool {
if output.count == 0 {
return false
}
output[0] = cast(u8)0
if !Hex64(account_id) || client_id.count == 0 ||
public_key.count == 0 {
return false
}
cursor: s64 = 0
if !WriteText(output, *cursor, "{\"user_id_hash\":") ||
!AppendJsonQuoted(output, *cursor, account_id) ||
!WriteText(output, *cursor, ",\"client_id\":") ||
!AppendJsonQuoted(output, *cursor, client_id) ||
!WriteText(output, *cursor, ",\"public_key\":") ||
!AppendJsonQuoted(output, *cursor, public_key) ||
!WriteByte(output, *cursor, cast(u8)125) {
output[0] = cast(u8)0
return false
}
return true
}
// The caller hashes the exact body bytes. This function fixes the signed
// message layout and prevents an app from choosing a different path or context.
#scope_export
#program_export
BuildLoginMessageHash :: (body_sha256_hex: string,
nonce_hex: string, output: []u8) -> bool {
if output.count == 0 {
return false
}
output[0] = cast(u8)0
if !Hex64(body_sha256_hex) || !Hex64(nonce_hex) {
return false
}
cursor: s64 = 0
if !WriteText(output, *cursor,
"daochi-sync-v1\nPOST\n/api/v1/sync/login\n") ||
!WriteText(output, *cursor, body_sha256_hex) ||
!WriteByte(output, *cursor, cast(u8)10) ||
!WriteText(output, *cursor, nonce_hex) ||
!WriteByte(output, *cursor, cast(u8)10) {
output[0] = cast(u8)0
return false
}
return true
}