From 0b4571f1d1da147269cf86ad75b4e526ecf220cc Mon Sep 17 00:00:00 2001 From: Aly Raffauf Date: Wed, 25 Nov 2026 20:09:58 -0500 Subject: [PATCH] feat(honcho): sign in with OAuth and refresh the grant The Honcho extension only accepted a static bearer key, so a sign-in that expires could not be used and each daemon had no way to get its own credential. Add a device-grant sign-in named for the daemon's sign-in service, keep the completed grant under honcho in creds.json, and refresh its access token under a file lock before expiry, writing the rotated grant back under the settings lock. A refused grant pauses delivery with the reason instead of retrying a dead token. --- extensions/honcho/gleam.toml | 1 + extensions/honcho/manifest.toml | 1 + extensions/honcho/src/albedo_ext_honcho.gleam | 2 + .../honcho/src/albedo_ext_honcho/config.gleam | 34 +- .../honcho/src/albedo_ext_honcho/oauth.gleam | 350 ++++++++++++++++++ .../src/albedo_ext_honcho/sign_in.gleam | 110 ++++++ .../honcho/test/albedo_ext_honcho_test.gleam | 147 +++++++- robot-docs/honcho.md | 14 +- 8 files changed, 644 insertions(+), 15 deletions(-) create mode 100644 extensions/honcho/src/albedo_ext_honcho/oauth.gleam create mode 100644 extensions/honcho/src/albedo_ext_honcho/sign_in.gleam diff --git a/extensions/honcho/gleam.toml b/extensions/honcho/gleam.toml index 7a12dc3e8..462435ee4 100644 --- a/extensions/honcho/gleam.toml +++ b/extensions/honcho/gleam.toml @@ -18,6 +18,7 @@ albedo_http = { path = "../../packages/albedo_http" } albedo_clock = { path = "../../packages/albedo_clock" } albedo_bytes = { path = "../../packages/albedo_bytes" } albedo_process = { path = "../../packages/albedo_process" } +albedo_file = { path = "../../packages/albedo_file" } albedo_sdk = { path = "../../packages/albedo_sdk" } [dev_dependencies] diff --git a/extensions/honcho/manifest.toml b/extensions/honcho/manifest.toml index 0cc3eb2e7..a4c4da974 100644 --- a/extensions/honcho/manifest.toml +++ b/extensions/honcho/manifest.toml @@ -47,6 +47,7 @@ packages = [ [requirements] albedo_bytes = { path = "../../packages/albedo_bytes" } albedo_clock = { path = "../../packages/albedo_clock" } +albedo_file = { path = "../../packages/albedo_file" } albedo_http = { path = "../../packages/albedo_http" } albedo_process = { path = "../../packages/albedo_process" } albedo_sdk = { path = "../../packages/albedo_sdk" } diff --git a/extensions/honcho/src/albedo_ext_honcho.gleam b/extensions/honcho/src/albedo_ext_honcho.gleam index 7982c1f92..403081a2a 100644 --- a/extensions/honcho/src/albedo_ext_honcho.gleam +++ b/extensions/honcho/src/albedo_ext_honcho.gleam @@ -5,6 +5,7 @@ import albedo_ext_honcho/config import albedo_ext_honcho/delivery import albedo_ext_honcho/discord import albedo_ext_honcho/ledger +import albedo_ext_honcho/sign_in import albedo_ext_honcho/worker import albedo_sdk/capability import albedo_sdk/extension @@ -91,6 +92,7 @@ fn definition( [], [ extension.SettingsPlugin(config.declaration()), + extension.LoginResolverPlugin(sign_in.resolve, sign_in.keep), extension.StartupPlugin(start), ..delivery.plugins() ], diff --git a/extensions/honcho/src/albedo_ext_honcho/config.gleam b/extensions/honcho/src/albedo_ext_honcho/config.gleam index 5603ebb85..d7e879d6e 100644 --- a/extensions/honcho/src/albedo_ext_honcho/config.gleam +++ b/extensions/honcho/src/albedo_ext_honcho/config.gleam @@ -1,6 +1,7 @@ //// The destination is the durable identity of an enrollment. Keys stay in //// the credential store and are read only when a request is sent. +import albedo_ext_honcho/oauth import albedo_sdk/credentials import albedo_sdk/profiles import albedo_sdk/settings @@ -89,6 +90,15 @@ pub fn discord() -> Result(Destination, String) { } } +/// The configured endpoint, or the hosted one when the section cannot be +/// read. Sign-in starts from this before a destination is configured. +pub fn endpoint() -> String { + case settings.load_section(section()) { + Ok(dest) -> dest.endpoint + Error(_) -> "https://api.honcho.dev" + } +} + pub fn load() -> Result(Destination, String) { use dest <- result.try(settings.load_section(section())) case dest.workspace, dest.human { @@ -151,16 +161,13 @@ fn valid_bytes(bytes: BitArray) -> Bool { } /// A multi-request operation can outlive a configuration change. Check the -/// destination after loading the key so a queued request for the old account -/// cannot take the new account's credential. +/// destination after loading the credential so a queued request for the old +/// account cannot take the new account's credential. A stored OAuth grant +/// refreshes its access token here; a static `apiKey` is used as saved. pub fn api_key(dest: Destination) -> Result(String, String) { let missing = "Set honcho.apiKey in creds.json to a valid bearer key" - use key <- result.try( - credentials.service( - settings.home(), - "honcho", - decode.at(["apiKey"], decode.string), - ) + use stored <- result.try( + credentials.service(settings.home(), "honcho", oauth.decoder()) |> result.replace_error(missing), ) use current <- result.try(discord()) @@ -169,9 +176,12 @@ pub fn api_key(dest: Destination) -> Result(String, String) { Discord -> current.endpoint == dest.endpoint && current.workspace == dest.workspace } - case valid, key != "" && profiles.valid_api_key(key) { - False, _ -> Error("Honcho destination changed") - True, True -> Ok(key) - True, False -> Error(missing) + use key <- result.try(case valid { + False -> Error("Honcho destination changed") + True -> oauth.access(settings.home(), dest.endpoint, stored) + }) + case key != "" && profiles.valid_api_key(key) { + True -> Ok(key) + False -> Error(missing) } } diff --git a/extensions/honcho/src/albedo_ext_honcho/oauth.gleam b/extensions/honcho/src/albedo_ext_honcho/oauth.gleam new file mode 100644 index 000000000..2f9fa850c --- /dev/null +++ b/extensions/honcho/src/albedo_ext_honcho/oauth.gleam @@ -0,0 +1,350 @@ +//// A Honcho sign-in that refreshes itself. The stored credential mirrors the +//// shape a Hermes `honcho.json` host block uses, so a grant can be copied +//// across: `apiKey` holds the current access token and `oauth` the rotating +//// refresh grant. Refresh tokens are single-use, so exchanges run under a +//// file lock and the rotation is written back before the token is used. + +import albedo_clock +import albedo_file +import albedo_http/buffered +import albedo_sdk/credentials +import albedo_sdk/http +import albedo_sdk/settings_documents +import gleam/bit_array +import gleam/dict.{type Dict} +import gleam/dynamic.{type Dynamic} +import gleam/dynamic/decode +import gleam/int +import gleam/json +import gleam/list +import gleam/option.{type Option, None, Some} +import gleam/result + +/// Refresh this long before the access token expires. +const skew_seconds = 120 + +const refresh_wait_ms = 30_000 + +pub type Grant { + Grant( + refresh_token: String, + expires_at: Int, + client_id: String, + token_endpoint: String, + scope: String, + token_type: String, + ) +} + +pub type Stored { + Stored(access: String, grant: Option(Grant)) +} + +pub fn decoder() -> decode.Decoder(Stored) { + use access <- decode.optional_field("apiKey", "", decode.string) + use grant <- decode.optional_field( + "oauth", + None, + decode.optional(grant_decoder()), + ) + decode.success(Stored(access, grant)) +} + +fn grant_decoder() -> decode.Decoder(Grant) { + use refresh_token <- decode.field("refreshToken", decode.string) + use expires_at <- decode.optional_field("expiresAt", 0, decode.int) + use client_id <- decode.optional_field("clientId", "", decode.string) + use token_endpoint <- decode.optional_field( + "tokenEndpoint", + "", + decode.string, + ) + use scope <- decode.optional_field("scope", "write", decode.string) + use token_type <- decode.optional_field("tokenType", "Bearer", decode.string) + decode.success(Grant( + refresh_token, + expires_at, + client_id, + token_endpoint, + scope, + token_type, + )) +} + +fn now_seconds() -> Int { + albedo_clock.system_ms() / 1000 +} + +/// Whether `access` can be sent without refreshing at `now` seconds. +pub fn fresh(access: String, grant: Grant, now: Int) -> Bool { + access != "" && grant.expires_at - now > skew_seconds +} + +/// The bearer token to send: the stored access token when it is fresh, a +/// refreshed one when a grant can renew it, or the stored token unchanged +/// when no grant is saved. +pub fn access( + home: String, + endpoint: String, + stored: Stored, +) -> Result(String, String) { + case stored.grant { + None -> Ok(stored.access) + Some(grant) -> + case fresh(stored.access, grant, now_seconds()) { + True -> Ok(stored.access) + False -> refreshed(home, endpoint, stored) + } + } +} + +fn refreshed( + home: String, + endpoint: String, + stored: Stored, +) -> Result(String, String) { + let run = fn() { refresh_locked(home, endpoint) } + case + albedo_file.with_lock( + albedo_file.join(home, "honcho-oauth"), + albedo_file.Within(refresh_wait_ms), + run, + ) + { + Ok(answer) -> answer + // Another process is refreshing. A token that has not expired yet is + // still worth sending; an expired one must wait for the next attempt. + Error(Nil) -> + case stored.grant { + Some(grant) -> + case stored.access != "" && grant.expires_at > now_seconds() { + True -> Ok(stored.access) + False -> + Error("Honcho sign-in is still refreshing; try again shortly") + } + _ -> Error("Honcho sign-in is still refreshing; try again shortly") + } + } +} + +fn refresh_locked(home: String, endpoint: String) -> Result(String, String) { + use stored <- result.try( + credentials.service(home, "honcho", decoder()) + |> result.replace_error("Honcho credential is unavailable"), + ) + case stored.grant { + None -> Ok(stored.access) + Some(grant) -> + case fresh(stored.access, grant, now_seconds()) { + // Another process refreshed while this one waited for the lock. + True -> Ok(stored.access) + False -> exchange(home, endpoint, stored, grant) + } + } +} + +fn exchange( + home: String, + endpoint: String, + stored: Stored, + grant: Grant, +) -> Result(String, String) { + let url = case grant.token_endpoint { + "" -> endpoint <> "/oauth/token" + saved -> saved + } + let fields = [ + #("grant_type", "refresh_token"), + #("refresh_token", grant.refresh_token), + #("client_id", grant.client_id), + ] + case http.post_form(url, [], fields, buffered.Timeouts(15_000, 15_000)) { + Ok(#(status, body)) if status >= 200 && status < 300 -> + case renewed(stored, body, now_seconds()) { + Ok(next) -> { + persist(home, next) + Ok(next.access) + } + Error(reason) -> Error(reason) + } + Ok(#(status, body)) -> + case credentials.refused(status, body) { + True -> + Error( + "Honcho sign-in was refused; sign in again and update the honcho credentials in creds.json", + ) + False -> + transient( + stored, + grant, + "Honcho returned HTTP " <> int.to_string(status), + ) + } + Error(reason) -> transient(stored, grant, reason) + } +} + +/// A refresh that could not be completed leaves a not-yet-expired token +/// usable; an expired one reports the failure. +fn transient( + stored: Stored, + grant: Grant, + reason: String, +) -> Result(String, String) { + case stored.access != "" && grant.expires_at > now_seconds() { + True -> Ok(stored.access) + False -> Error("Could not refresh the Honcho sign-in: " <> reason) + } +} + +/// The credential after a successful token response, keeping the saved +/// refresh token and grant fields the response does not repeat. +pub fn renewed( + stored: Stored, + body: BitArray, + now: Int, +) -> Result(Stored, String) { + use grant <- result.try(option.to_result( + stored.grant, + "Honcho credential has no sign-in to refresh", + )) + let tokens = { + use access <- decode.field("access_token", decode.string) + use refresh <- decode.optional_field( + "refresh_token", + grant.refresh_token, + decode.string, + ) + use expires_in <- decode.optional_field("expires_in", 3600, decode.int) + use scope <- decode.optional_field("scope", grant.scope, decode.string) + use token_type <- decode.optional_field( + "token_type", + grant.token_type, + decode.string, + ) + decode.success(#(access, refresh, expires_in, scope, token_type)) + } + use #(access, refresh, expires_in, scope, token_type) <- result.try( + json_tokens(body, tokens), + ) + case access { + "" -> Error("Honcho token response had no access token") + _ -> + Ok(Stored( + access, + Some(Grant( + refresh, + now + expires_in, + grant.client_id, + grant.token_endpoint, + scope, + token_type, + )), + )) + } +} + +fn json_tokens( + body: BitArray, + decoder: decode.Decoder(a), +) -> Result(a, String) { + use text <- result.try( + bit_array.to_string(body) + |> result.replace_error("Honcho token response was not text"), + ) + json.parse(text, decoder) + |> result.replace_error("Honcho token response was not the expected shape") +} + +/// The credential as saved under `honcho` in creds.json. +pub fn encode(stored: Stored) -> Dict(String, Dynamic) { + case stored.grant { + Some(grant) -> + dict.from_list([ + #("apiKey", dynamic.string(stored.access)), + #("oauth", grant_dynamic(grant)), + ]) + None -> dict.from_list([#("apiKey", dynamic.string(stored.access))]) + } +} + +/// The credential from a completed sign-in's token response. A sign-in +/// without a refresh token cannot renew itself, so it does not complete. +pub fn granted( + tokens: Dict(String, Dynamic), + client_id: String, + token_endpoint: String, + now: Int, +) -> Result(Stored, String) { + let fields = { + use access <- decode.field("access_token", decode.string) + use refresh <- decode.field("refresh_token", decode.string) + use expires_in <- decode.optional_field("expires_in", 3600, decode.int) + use scope <- decode.optional_field("scope", "write", decode.string) + use token_type <- decode.optional_field( + "token_type", + "Bearer", + decode.string, + ) + decode.success(#(access, refresh, expires_in, scope, token_type)) + } + use #(access, refresh, expires_in, scope, token_type) <- result.try( + decode.run(to_dynamic(tokens), fields) + |> result.replace_error( + "Honcho sign-in did not return a refreshable credential", + ), + ) + case access, refresh { + "", _ | _, "" -> + Error("Honcho sign-in did not return a refreshable credential") + _, _ -> + Ok(Stored( + access, + Some(Grant( + refresh, + now + expires_in, + client_id, + token_endpoint, + scope, + token_type, + )), + )) + } +} + +fn persist(home: String, stored: Stored) -> Nil { + let _ = + settings_documents.with_lock(home, fn() { + use creds <- result.try(settings_documents.read(home, "creds.json")) + use document <- result.try( + decode.run(creds, decode.dict(decode.string, decode.dynamic)) + |> result.replace_error("invalid settings"), + ) + use section <- result.try(settings_documents.object(creds, "honcho")) + let section = dict.merge(section, encode(stored)) + let document = dict.insert(document, "honcho", to_dynamic(section)) + settings_documents.commit_group( + home, + dict.from_list([#("creds.json", to_dynamic(document))]), + ) + }) + Nil +} + +fn grant_dynamic(grant: Grant) -> Dynamic { + dynamic.properties([ + #(dynamic.string("refreshToken"), dynamic.string(grant.refresh_token)), + #(dynamic.string("expiresAt"), dynamic.int(grant.expires_at)), + #(dynamic.string("clientId"), dynamic.string(grant.client_id)), + #(dynamic.string("tokenEndpoint"), dynamic.string(grant.token_endpoint)), + #(dynamic.string("scope"), dynamic.string(grant.scope)), + #(dynamic.string("tokenType"), dynamic.string(grant.token_type)), + ]) +} + +fn to_dynamic(values: Dict(String, Dynamic)) -> Dynamic { + values + |> dict.to_list + |> list.map(fn(entry) { #(dynamic.string(entry.0), entry.1) }) + |> dynamic.properties +} diff --git a/extensions/honcho/src/albedo_ext_honcho/sign_in.gleam b/extensions/honcho/src/albedo_ext_honcho/sign_in.gleam new file mode 100644 index 000000000..876e20e21 --- /dev/null +++ b/extensions/honcho/src/albedo_ext_honcho/sign_in.gleam @@ -0,0 +1,110 @@ +//// Sign in to Honcho from any Albedo client. Honcho's OAuth client is +//// `hermes-agent` for every surface, and its authorization server offers a +//// device grant, so a daemon on another host can sign in: the client shows +//// a code, the person confirms it in their browser, and the daemon polls +//// for the grant. The completed credential is kept under `honcho` in +//// creds.json in the shape the OAuth module refreshes, not as a provider +//// account. + +import albedo_clock +import albedo_ext_honcho/config +import albedo_ext_honcho/oauth as honcho_auth +import albedo_sdk/oauth +import gleam/dict.{type Dict} +import gleam/dynamic.{type Dynamic} +import gleam/dynamic/decode +import gleam/list +import gleam/option.{type Option, None, Some} +import gleam/result + +const client_id = "hermes-agent" + +/// The sign-in for `provider` when it is Honcho's. +pub fn resolve( + _home: String, + provider: String, +) -> Option(Result(oauth.Login, String)) { + case provider { + "honcho" -> Some(Ok(login())) + _ -> None + } +} + +/// creds.json with a completed Honcho sign-in's credential in place of the +/// saved `honcho` section. Other sections are kept. +pub fn keep(creds: Dynamic, provider: String, credential: Dynamic) -> Dynamic { + case provider { + "honcho" -> { + let document = + decode.run(creds, decode.dict(decode.string, decode.dynamic)) + |> result.unwrap(dict.new()) + let section = + decode.run(credential, decode.dict(decode.string, decode.dynamic)) + |> result.unwrap(dict.new()) + document + |> dict.insert("honcho", to_dynamic(section)) + |> to_dynamic + } + _ -> creds + } +} + +fn login() -> oauth.Login { + oauth.Login( + "honcho", + "sign in to honcho", + "conversation memory", + oauth.Service, + "honcho", + oauth.device(device_flow), + fn(_) { Ok("") }, + fn(_, _, _) { Error("Honcho sign-in uses a device code") }, + account, + None, + ) +} + +fn device_flow() -> oauth.DeviceFlow { + let endpoint = config.endpoint() + oauth.DeviceFlow( + server: endpoint, + code_path: "/oauth/device_authorization", + token_path: "/oauth/token", + payload: oauth.Form( + code: [#("client_id", client_id), #("scope", "write")], + token: [ + #("client_id", client_id), + #("grant_type", "urn:ietf:params:oauth:grant-type:device_code"), + ], + ), + headers: [#("accept", "application/json")], + progress: "Waiting for authorization in your browser…", + instructions: fn(code, url) { + "Open " <> url <> " and confirm code " <> code <> " to sign in to Honcho." + }, + credential: fn(tokens) { + honcho_auth.granted( + tokens, + client_id, + endpoint <> "/oauth/token", + albedo_clock.system_ms() / 1000, + ) + |> result.map(honcho_auth.encode) + }, + ) +} + +fn account(_credential: Dynamic) -> oauth.Account { + let detail = case config.load() { + Ok(dest) -> dest.workspace <> " · " <> dest.human + Error(_) -> "conversation memory" + } + oauth.account("honcho", "Honcho", detail, False) +} + +fn to_dynamic(values: Dict(String, Dynamic)) -> Dynamic { + values + |> dict.to_list + |> list.map(fn(entry) { #(dynamic.string(entry.0), entry.1) }) + |> dynamic.properties +} diff --git a/extensions/honcho/test/albedo_ext_honcho_test.gleam b/extensions/honcho/test/albedo_ext_honcho_test.gleam index e1589583c..ba169690d 100644 --- a/extensions/honcho/test/albedo_ext_honcho_test.gleam +++ b/extensions/honcho/test/albedo_ext_honcho_test.gleam @@ -1,8 +1,14 @@ import albedo_ext_honcho/generated/sql/ledger_sql as sql import albedo_ext_honcho/ledger +import albedo_ext_honcho/oauth +import albedo_ext_honcho/sign_in import albedo_sdk/follow +import gleam/dict +import gleam/dynamic import gleam/dynamic/decode -import gleam/option.{None} +import gleam/json +import gleam/list +import gleam/option.{None, Some} import gleeunit import sqlight @@ -10,6 +16,145 @@ pub fn main() -> Nil { gleeunit.main() } +fn grant(expires_at: Int) -> oauth.Grant { + oauth.Grant("hch-rt-old", expires_at, "hermes-agent", "", "write", "Bearer") +} + +pub fn oauth_decoder_reads_a_hermes_shaped_credential_test() -> Nil { + let saved = + dynamic.properties([ + #(dynamic.string("apiKey"), dynamic.string("hch-at-old")), + #( + dynamic.string("oauth"), + dynamic.properties([ + #(dynamic.string("refreshToken"), dynamic.string("hch-rt-old")), + #(dynamic.string("expiresAt"), dynamic.int(2000)), + #(dynamic.string("clientId"), dynamic.string("hermes-agent")), + #( + dynamic.string("tokenEndpoint"), + dynamic.string("https://api.honcho.dev/oauth/token"), + ), + #(dynamic.string("scope"), dynamic.string("write")), + #(dynamic.string("tokenType"), dynamic.string("Bearer")), + ]), + ), + ]) + let assert Ok(stored) = decode.run(saved, oauth.decoder()) + let assert "hch-at-old" = stored.access + let assert Some(saved_grant) = stored.grant + let assert "hch-rt-old" = saved_grant.refresh_token + let assert 2000 = saved_grant.expires_at + let assert "https://api.honcho.dev/oauth/token" = saved_grant.token_endpoint + Nil +} + +pub fn oauth_granted_builds_a_refreshable_credential_test() -> Nil { + let tokens = + dict.from_list([ + #("access_token", dynamic.string("hch-at-new")), + #("refresh_token", dynamic.string("hch-rt-new")), + #("expires_in", dynamic.int(3600)), + ]) + let assert Ok(stored) = + oauth.granted( + tokens, + "hermes-agent", + "https://api.honcho.dev/oauth/token", + 5000, + ) + let assert "hch-at-new" = stored.access + let assert Some(saved_grant) = stored.grant + let assert 8600 = saved_grant.expires_at + let assert "https://api.honcho.dev/oauth/token" = saved_grant.token_endpoint + + // The encoded credential decodes back to the same grant. + let assert Ok(round_trip) = + decode.run(oauth.encode(stored) |> to_dynamic, oauth.decoder()) + let assert Some(round_trip_grant) = round_trip.grant + let assert "hch-rt-new" = round_trip_grant.refresh_token + + // A sign-in without a refresh token does not complete. + let assert Error(_) = + oauth.granted( + dict.from_list([#("access_token", dynamic.string("hch-at-new"))]), + "hermes-agent", + "https://api.honcho.dev/oauth/token", + 5000, + ) + Nil +} + +pub fn sign_in_keep_replaces_the_honcho_section_test() -> Nil { + let creds = + dynamic.properties([ + #(dynamic.string("other"), dynamic.string("kept")), + #( + dynamic.string("honcho"), + dynamic.properties([ + #(dynamic.string("apiKey"), dynamic.string("hch-at-old")), + ]), + ), + ]) + let credential = + dynamic.properties([ + #(dynamic.string("apiKey"), dynamic.string("hch-at-new")), + ]) + let kept = sign_in.keep(creds, "honcho", credential) + let assert Ok(section) = + decode.run(kept, decode.at(["honcho", "apiKey"], decode.string)) + let assert "hch-at-new" = section + let assert Ok(other) = decode.run(kept, decode.at(["other"], decode.string)) + let assert "kept" = other + // Other providers are left alone. + let assert True = sign_in.keep(creds, "other", credential) == creds + Nil +} + +fn to_dynamic(values: dict.Dict(String, dynamic.Dynamic)) -> dynamic.Dynamic { + values + |> dict.to_list + |> list.map(fn(entry) { #(dynamic.string(entry.0), entry.1) }) + |> dynamic.properties +} + +pub fn oauth_freshness_uses_the_expiry_skew_test() -> Nil { + let assert True = oauth.fresh("hch-at-a", grant(1000), 800) + let assert False = oauth.fresh("hch-at-a", grant(1000), 900) + let assert False = oauth.fresh("", grant(1000), 800) + Nil +} + +pub fn oauth_renewed_rotates_and_keeps_the_grant_test() -> Nil { + let stored = oauth.Stored("hch-at-old", Some(grant(1000))) + let body = + json.object([ + #("access_token", json.string("hch-at-new")), + #("refresh_token", json.string("hch-rt-new")), + #("expires_in", json.int(3600)), + ]) + |> json.to_string + let assert Ok(next) = oauth.renewed(stored, <>, 5000) + let assert "hch-at-new" = next.access + let assert Some(next_grant) = next.grant + let assert "hch-rt-new" = next_grant.refresh_token + let assert 8600 = next_grant.expires_at + let assert "hermes-agent" = next_grant.client_id + + // A response without a new refresh token keeps the saved one. + let kept = + json.object([#("access_token", json.string("hch-at-next"))]) + |> json.to_string + let assert Ok(next) = oauth.renewed(stored, <>, 5000) + let assert Some(next_grant) = next.grant + let assert "hch-rt-old" = next_grant.refresh_token + let assert 8600 = next_grant.expires_at + + let assert Error(_) = oauth.renewed(stored, <<"not json":utf8>>, 5000) + let assert Error(_) = + oauth.renewed(oauth.Stored("hch-at-old", None), <>, 5000) + Nil +} + pub fn rewind_trims_the_queue_and_preserves_remote_receipts_test() -> Nil { use db <- sqlight.with_connection(":memory:") let assert Ok(_) = diff --git a/robot-docs/honcho.md b/robot-docs/honcho.md index eb01f1c6a..c7164093f 100644 --- a/robot-docs/honcho.md +++ b/robot-docs/honcho.md @@ -23,8 +23,18 @@ self-hosted server to use it in place of the default hosted endpoint. } ``` -Store the bearer key under `honcho.apiKey` in `creds.json`. The extension reads -the key when making a request. The +Sign in from an Albedo client with the Honcho sign-in, or store a bearer key +under `honcho.apiKey` in `creds.json` by hand. Sign-in uses Honcho's device +grant: the client shows a code, you confirm it in your browser, and the daemon +saves its own grant under `honcho` in `creds.json`. The +[sign-in module](../extensions/honcho/src/albedo_ext_honcho/sign_in.gleam) names +that sign-in for the daemon's sign-in service. The +[OAuth module](../extensions/honcho/src/albedo_ext_honcho/oauth.gleam) refreshes +the access token before it expires, writes the rotated grant back under the +settings lock, and reports a refused grant as a paused delivery. Refresh tokens +are single-use, so give each daemon its own sign-in instead of copying a grant +another program refreshes, such as the one Hermes keeps in its `honcho.json`. +The [configuration module](../extensions/honcho/src/albedo_ext_honcho/config.gleam) owns field validation. See [settings](settings.md) for daemon settings and credentials. -- knotmirror 0.0.1