/*
* The session with the account's server (its PDS): signing in with an
* app password, the two tokens that come of it, and every call made with
* them. The tokens are kept in the wallet (libsecret) under the account's
* DID, so the app and the tile provider share them; the access token
* lasts a couple of hours and a call refused for an old one is made
* again after asking for new ones. Two programs may find it old at once:
* whoever does looks in the wallet first, where the other may already
* have put the new ones.
*/
#include <gio/gio.h>
#include <libsecret/secret.h>
#include <string.h>
#include "http.h"
#include "sky.h"
#define WALLET_S 20 // a stuck or locked wallet is given up on
#define PUBLIC_API "https://public.api.bsky.app"
#define DIRECTORY "https://plc.directory"
#define DEFAULT_SERVER "https://bsky.social"
#define EXPIRED "Your session has ended. Sign in again."
static const SecretSchema schema = {
"org.cont8nuum.Cirrus.Session", SECRET_SCHEMA_NONE,
{
{ "account", SECRET_SCHEMA_ATTRIBUTE_STRING },
{ NULL, 0 },
},
};
struct call {
char *method, *call, *body, *upload, *mime;
sky_fn fn;
void *data;
unsigned gen;
bool retried; // already sent again after new tokens
};
unsigned sky_generation = 1;
static GQueue waiting; // calls held until the tokens are there
static bool loading, refreshing;
static void (*expired_fn)(void *data);
static void *expired_data;
static void send(struct call *c);
void sky_on_expired(void (*fn)(void *data), void *data) {
expired_fn = fn;
expired_data = data;
}
/* Words for an answer that isn't a 200 */
static const char *words(int status, const struct json *json) {
static char buf[64];
if (status == 0) {
return "Couldn't reach the server.";
}
const char *message = json_str(json_get(json, "message"), "");
if (message[0]) {
return message;
}
g_snprintf(buf, sizeof(buf), "The server said no (%d).", status);
return buf;
}
static void finish(struct call *c, int status, struct json *json,
const char *error) {
c->fn(status, json, error, c->data);
json_free(json);
g_free(c->method);
g_free(c->call);
g_free(c->body);
g_free(c->upload);
g_free(c->mime);
g_free(c);
}
/* Everything held is sent (send holds it again if it must) */
static void flush(void) {
GQueue held = waiting;
g_queue_init(&waiting);
struct call *c;
while ((c = g_queue_pop_head(&held))) {
send(c);
}
}
static void fail_waiting(int status, const char *error) {
GQueue held = waiting;
g_queue_init(&waiting);
struct call *c;
while ((c = g_queue_pop_head(&held))) {
finish(c, c->gen == sky_generation ? status : 0, NULL,
c->gen == sky_generation ? error : NULL);
}
}
static void set_tokens(struct sky_account *a, const char *access,
const char *refresh) {
if (a->access) {
memset(a->access, 0, strlen(a->access));
}
if (a->refresh) {
memset(a->refresh, 0, strlen(a->refresh));
}
g_free(a->access);
g_free(a->refresh);
a->access = g_strdup(access);
a->refresh = g_strdup(refresh);
}
static void session_expired(struct sky_account *a) {
a->expired = true;
bool current = a == sky_me;
if (current) {
fail_waiting(401, EXPIRED);
if (expired_fn) {
expired_fn(expired_data);
}
}
}
/* The wallet */
struct wallet {
char *did;
GCancellable *cancel;
guint timeout;
bool refresh; // looked at before asking the server for new tokens
};
static gboolean wallet_late(gpointer data) {
struct wallet *w = data;
w->timeout = 0;
g_cancellable_cancel(w->cancel);
return G_SOURCE_REMOVE;
}
static struct wallet *wallet_new(struct sky_account *a) {
struct wallet *w = g_new0(struct wallet, 1);
w->did = g_strdup(a->did);
w->cancel = g_cancellable_new();
w->timeout = g_timeout_add_seconds(WALLET_S, wallet_late, w);
return w;
}
static void wallet_free(struct wallet *w) {
if (w->timeout) {
g_source_remove(w->timeout);
}
g_object_unref(w->cancel);
g_free(w->did);
g_free(w);
}
static void stored(GObject *source, GAsyncResult *res, gpointer data) {
GError *error = NULL;
if (!secret_password_store_finish(res, &error)) {
g_warning("wallet: %s", error ? error->message : "?");
g_clear_error(&error);
}
wallet_free(data);
}
static void store_tokens(struct sky_account *a) {
char *value = g_strdup_printf("%s\n%s", a->refresh ? a->refresh : "",
a->access ? a->access : "");
char *label = g_strdup_printf("Cirrus (%s)", a->handle);
struct wallet *w = wallet_new(a);
secret_password_store(&schema, SECRET_COLLECTION_DEFAULT, label, value,
w->cancel, stored, w, "account", a->did, NULL);
memset(value, 0, strlen(value));
g_free(value);
g_free(label);
}
static void refresh_now(struct sky_account *a);
static void looked_up(GObject *source, GAsyncResult *res, gpointer data) {
struct wallet *w = data;
GError *error = NULL;
char *secret = secret_password_lookup_finish(res, &error);
struct sky_account *a = sky_account_find(w->did);
bool for_refresh = w->refresh;
wallet_free(w);
if (for_refresh) {
/* Did another program of ours renew them meanwhile? */
char *nl = secret ? strchr(secret, '\n') : NULL;
if (a && nl && nl[1] && g_strcmp0(nl + 1, a->access) != 0) {
*nl = '\0';
set_tokens(a, nl + 1, secret);
refreshing = false;
flush();
} else if (a) {
refresh_now(a);
} else {
refreshing = false;
flush();
}
} else {
loading = false;
if (a == NULL) {
flush();
} else if (error) {
g_warning("wallet: %s", error->message);
if (a == sky_me) {
fail_waiting(0, "The wallet couldn't be read. Is it open?");
}
} else {
char *nl = secret ? strchr(secret, '\n') : NULL;
a->loaded = true;
if (nl && nl > secret) {
*nl = '\0';
set_tokens(a, nl + 1, secret);
flush();
} else {
/* Nothing there: signed in on a wallet that is gone */
session_expired(a);
flush();
}
}
}
g_clear_error(&error);
if (secret) {
memset(secret, 0, strlen(secret));
secret_password_free(secret);
}
}
static void load_tokens(struct sky_account *a) {
if (loading) {
return;
}
loading = true;
struct wallet *w = wallet_new(a);
secret_password_lookup(&schema, w->cancel, looked_up, w, "account",
a->did, NULL);
}
/* New tokens */
static void refreshed(int status, const char *body, void *data) {
char *did = data;
struct sky_account *a = sky_account_find(did);
g_free(did);
refreshing = false;
struct json *json = body ? json_parse(body) : NULL;
const char *access = json_str(json_get(json, "accessJwt"), "");
const char *refresh = json_str(json_get(json, "refreshJwt"), "");
if (a == NULL) {
flush();
} else if (status == 200 && access[0] && refresh[0]) {
set_tokens(a, access, refresh);
store_tokens(a);
flush();
} else if (status == 0 || status >= 500) {
if (a == sky_me) {
fail_waiting(status, words(status, json));
} else {
flush();
}
} else {
/* The server won't: the session is over */
g_message("refreshing the session: %d %s", status,
json_str(json_get(json, "error"), ""));
session_expired(a);
flush();
}
json_free(json);
}
static void refresh_now(struct sky_account *a) {
char *url = g_strconcat(a->pds, "/xrpc/com.atproto.server.refreshSession",
NULL);
c8_http(&(struct c8_http){ .method = "POST", .url = url,
.token = a->refresh, .accept = "application/json",
.agent = SKY_AGENT, .allow_http = sky_allow_http() }, refreshed,
g_strdup(a->did));
g_free(url);
}
static void start_refresh(struct sky_account *a) {
if (refreshing) {
return;
}
refreshing = true;
struct wallet *w = wallet_new(a);
w->refresh = true;
secret_password_lookup(&schema, w->cancel, looked_up, w, "account",
a->did, NULL);
}
/* Calls */
static void answered(int status, const char *body, void *data) {
struct call *c = data;
if (c->gen != sky_generation) {
finish(c, 0, NULL, NULL);
return;
}
struct json *json = body && body[0] ? json_parse(body) : NULL;
if (status == 200) {
finish(c, 200, json, NULL);
return;
}
const char *error = json_str(json_get(json, "error"), "");
if (!c->retried && sky_me && (strcmp(error, "ExpiredToken") == 0 ||
strcmp(error, "InvalidToken") == 0)) {
c->retried = true;
json_free(json);
g_queue_push_tail(&waiting, c);
start_refresh(sky_me);
return;
}
finish(c, status, json, words(status, json));
}
static void send(struct call *c) {
struct sky_account *a = sky_me;
if (c->gen != sky_generation) {
finish(c, 0, NULL, NULL);
return;
}
if (a == NULL) {
finish(c, 0, NULL, "Sign in first.");
return;
}
if (a->expired) {
finish(c, 401, NULL, EXPIRED);
return;
}
if (!a->loaded || refreshing) {
g_queue_push_tail(&waiting, c);
if (!a->loaded) {
load_tokens(a);
}
return;
}
char *url = g_strconcat(a->pds, "/xrpc/", c->call, NULL);
c8_http(&(struct c8_http){ .method = c->method, .url = url,
.body = c->body, .upload = c->upload, .content_type = c->mime,
.token = a->access, .accept = "application/json", .agent = SKY_AGENT,
.allow_http = sky_allow_http() }, answered, c);
g_free(url);
}
static struct call *call_new(const char *method, const char *call,
sky_fn fn, void *data) {
struct call *c = g_new0(struct call, 1);
c->method = g_strdup(method);
c->call = g_strdup(call);
c->fn = fn;
c->data = data;
c->gen = sky_generation;
return c;
}
void sky_get(const char *call, sky_fn fn, void *data) {
send(call_new("GET", call, fn, data));
}
void sky_post(const char *method, const char *body, sky_fn fn, void *data) {
struct call *c = call_new("POST", method, fn, data);
c->body = g_strdup(body ? body : "{}");
send(c);
}
void sky_upload(const char *path, const char *mime, sky_fn fn, void *data) {
struct call *c = call_new("POST", "com.atproto.repo.uploadBlob", fn, data);
c->upload = g_strdup(path);
c->mime = g_strdup(mime);
send(c);
}
struct public_call {
sky_fn fn;
void *data;
};
static void public_answered(int status, const char *body, void *data) {
struct public_call *p = data;
struct json *json = body && body[0] ? json_parse(body) : NULL;
p->fn(status, json, status == 200 ? NULL : words(status, json), p->data);
json_free(json);
g_free(p);
}
void sky_get_public(const char *url, sky_fn fn, void *data) {
struct public_call *p = g_new0(struct public_call, 1);
p->fn = fn;
p->data = data;
c8_http(&(struct c8_http){ .url = url, .accept = "application/json",
.agent = SKY_AGENT, .follow = true, .allow_http = sky_allow_http() },
public_answered, p);
}
/* Changing accounts */
void sky_use(struct sky_account *a) {
sky_me = a;
sky_generation++;
fail_waiting(0, NULL);
sky_save();
}
static void signed_out(int status, const char *body, void *data) {
/* Whatever it said, we have forgotten the session */
}
static void cleared(GObject *source, GAsyncResult *res, gpointer data) {
secret_password_clear_finish(res, NULL);
wallet_free(data);
}
void sky_sign_out(struct sky_account *a) {
if (a->refresh) {
char *url = g_strconcat(a->pds,
"/xrpc/com.atproto.server.deleteSession", NULL);
c8_http(&(struct c8_http){ .method = "POST", .url = url,
.token = a->refresh, .agent = SKY_AGENT,
.allow_http = sky_allow_http() }, signed_out, NULL);
g_free(url);
}
struct wallet *w = wallet_new(a);
secret_password_clear(&schema, w->cancel, cleared, w, "account", a->did,
NULL);
bool current = a == sky_me;
sky_account_remove(a);
if (current) {
sky_use(sky_accounts->len ? sky_accounts->pdata[0] : NULL);
} else {
sky_save();
}
}
/* Signing in */
struct signin {
char *identifier, *password, *server, *handle, *did;
sky_done_fn fn;
void *data;
};
static void signin_done(struct signin *s, const char *error) {
s->fn(error, s->data);
if (s->password) {
memset(s->password, 0, strlen(s->password));
}
g_free(s->identifier);
g_free(s->password);
g_free(s->server);
g_free(s->handle);
g_free(s->did);
g_free(s);
}
static void session_made(int status, const char *body, void *data) {
struct signin *s = data;
struct json *json = body && body[0] ? json_parse(body) : NULL;
const char *did = json_str(json_get(json, "did"), "");
const char *access = json_str(json_get(json, "accessJwt"), "");
const char *refresh = json_str(json_get(json, "refreshJwt"), "");
if (status == 200 && did[0] && access[0] && refresh[0]) {
struct sky_account *a = sky_account_add(did,
json_str(json_get(json, "handle"), s->identifier), s->server);
set_tokens(a, access, refresh);
a->loaded = true;
a->expired = false;
store_tokens(a);
sky_use(a);
signin_done(s, NULL);
} else {
const char *error = json_str(json_get(json, "error"), "");
const char *say = words(status, json);
if (strcmp(error, "AuthFactorTokenRequired") == 0) {
say = "This account asks for a code by email when its own "
"password is used. Make an app password in Bluesky's "
"settings (Privacy and security) and use that here.";
} else if (status == 401) {
say = "That handle or password isn't right.";
} else if (status == 0) {
say = "Couldn't reach the account's server.";
}
signin_done(s, say);
}
json_free(json);
}
static void make_session(struct signin *s) {
GString *body = g_string_new("{\"identifier\":");
sky_json_str(body, s->identifier);
g_string_append(body, ",\"password\":");
sky_json_str(body, s->password);
g_string_append_c(body, '}');
char *url = g_strconcat(s->server,
"/xrpc/com.atproto.server.createSession", NULL);
c8_http(&(struct c8_http){ .method = "POST", .url = url,
.body = body->str, .accept = "application/json", .agent = SKY_AGENT,
.allow_http = sky_allow_http() }, session_made, s);
g_free(url);
memset(body->str, 0, body->len);
g_string_free(body, TRUE);
}
/* The DID's document says which server holds the account */
static void got_document(int status, const char *body, void *data) {
struct signin *s = data;
struct json *json = body && body[0] ? json_parse(body) : NULL;
const char *server = NULL;
for (struct json *e = json_get(json, "service") ?
json_get(json, "service")->child : NULL; e; e = e->next) {
const char *id = json_str(json_get(e, "id"), "");
if (g_str_has_suffix(id, "#atproto_pds")) {
server = json_str(json_get(e, "serviceEndpoint"), NULL);
}
}
if (status == 200 && server && (g_str_has_prefix(server, "https://") ||
(sky_allow_http() && g_str_has_prefix(server, "http://")))) {
s->server = g_strdup(server);
/* No slash at its end */
size_t n = strlen(s->server);
while (n && s->server[n - 1] == '/') {
s->server[--n] = '\0';
}
make_session(s);
} else {
signin_done(s, status == 0 ? "Couldn't reach the directory that says "
"where accounts are." : "Couldn't find where that account is. "
"Type its server under the password.");
}
json_free(json);
}
static void find_server(struct signin *s) {
char *url = NULL;
if (g_str_has_prefix(s->did, "did:plc:")) {
url = g_strconcat(DIRECTORY, "/", s->did, NULL);
} else if (g_str_has_prefix(s->did, "did:web:") &&
strpbrk(s->did + 8, ":/%?#@") == NULL) {
url = g_strconcat("https://", s->did + 8, "/.well-known/did.json", NULL);
}
if (url == NULL) {
signin_done(s, "That isn't a kind of account this can find. Type its "
"server under the password.");
return;
}
c8_http(&(struct c8_http){ .url = url, .accept = "application/json",
.agent = SKY_AGENT, .follow = true }, got_document, s);
g_free(url);
}
static bool is_did(const char *text) {
if (!g_str_has_prefix(text, "did:plc:") &&
!g_str_has_prefix(text, "did:web:")) {
return false;
}
for (const char *p = text; *p; p++) {
if (!g_ascii_isalnum(*p) && strchr(":.-_%", *p) == NULL) {
return false;
}
}
return strlen(text) < 256;
}
static void handle_resolved(int status, const char *body, void *data) {
struct signin *s = data;
struct json *json = body && body[0] ? json_parse(body) : NULL;
const char *did = json_str(json_get(json, "did"), "");
if (status == 200 && is_did(did)) {
s->did = g_strdup(did);
find_server(s);
} else {
signin_done(s, status == 0 ? "Couldn't reach Bluesky to look that "
"handle up." : "There's no account with that handle.");
}
json_free(json);
}
/* The handle's own site may say who it is; else Bluesky is asked */
static void got_well_known(int status, const char *body, void *data) {
struct signin *s = data;
char *did = body ? g_strstrip(g_strndup(body, 300)) : NULL;
if (status == 200 && did && is_did(did)) {
s->did = did;
find_server(s);
return;
}
g_free(did);
char *escaped = g_uri_escape_string(s->handle, NULL, FALSE);
char *url = g_strconcat(PUBLIC_API,
"/xrpc/com.atproto.identity.resolveHandle?handle=", escaped, NULL);
c8_http(&(struct c8_http){ .url = url, .accept = "application/json",
.agent = SKY_AGENT }, handle_resolved, s);
g_free(url);
g_free(escaped);
}
static bool is_handle(const char *text) {
if (strchr(text, '.') == NULL || strlen(text) > 253) {
return false;
}
for (const char *p = text; *p; p++) {
if (!g_ascii_isalnum(*p) && *p != '.' && *p != '-') {
return false;
}
}
return text[0] != '.' && text[0] != '-';
}
void sky_sign_in(const char *identifier, const char *password,
const char *server, sky_done_fn fn, void *data) {
struct signin *s = g_new0(struct signin, 1);
s->fn = fn;
s->data = data;
char *id = g_strstrip(g_strdup(identifier));
s->identifier = g_strdup(id[0] == '@' ? id + 1 : id);
g_free(id);
s->password = g_strstrip(g_strdup(password));
char *srv = g_strstrip(g_strdup(server ? server : ""));
if (s->identifier[0] == '\0' || s->password[0] == '\0') {
g_free(srv);
signin_done(s, "Type your handle and an app password.");
return;
}
if (srv[0]) {
s->server = strstr(srv, "://") ? g_strdup(srv) :
g_strconcat("https://", srv, NULL);
size_t n = strlen(s->server);
while (n && s->server[n - 1] == '/') {
s->server[--n] = '\0';
}
g_free(srv);
make_session(s);
return;
}
g_free(srv);
if (strchr(s->identifier, '@')) {
/* An email says nothing of where the account is */
s->server = g_strdup(DEFAULT_SERVER);
make_session(s);
return;
}
if (is_did(s->identifier)) {
s->did = g_strdup(s->identifier);
find_server(s);
return;
}
if (strchr(s->identifier, '.') == NULL) {
/* Just a name: one of bsky.social's */
char *full = g_strconcat(s->identifier, ".bsky.social", NULL);
g_free(s->identifier);
s->identifier = full;
}
if (!is_handle(s->identifier)) {
signin_done(s, "That doesn't look like a handle. They are like "
"name.bsky.social.");
return;
}
s->handle = g_ascii_strdown(s->identifier, -1);
char *url = g_strconcat("https://", s->handle, "/.well-known/atproto-did",
NULL);
c8_http(&(struct c8_http){ .url = url, .accept = "text/plain",
.agent = SKY_AGENT }, got_well_known, s);
g_free(url);
}