Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

fix(bots): hash bot tokens at rest and mint credentials on click (#5867)

teo8835e3a2b144
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.json
index a98f6f4716..4329036fd6 100644
--- a/.github/workspace-dep-closures.json
+++ b/.github/workspace-dep-closures.json
@@ -22,6 +22,7 @@
"crates/ai_usage",
"crates/attachment",
"crates/bot_id",
+ "crates/bot_token",
"crates/cowlike",
"crates/macro_auth",
"crates/macro_authorization",
@@ -59,6 +60,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/bot_token",
"crates/bots",
"crates/broadcast",
"crates/call",
@@ -138,6 +140,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/bot_token",
"crates/bots",
"crates/broadcast",
"crates/call",
@@ -226,6 +229,7 @@
"crates/ai_usage",
"crates/attachment",
"crates/bot_id",
+ "crates/bot_token",
"crates/bots",
"crates/broadcast",
"crates/channel_sender",
@@ -284,6 +288,7 @@
"crates/ai_usage",
"crates/attachment",
"crates/bot_id",
+ "crates/bot_token",
"crates/bots",
"crates/broadcast",
"crates/channel_sender",
@@ -342,6 +347,7 @@
"crates/ai_usage",
"crates/attachment",
"crates/bot_id",
+ "crates/bot_token",
"crates/bots",
"crates/broadcast",
"crates/channel_sender",
@@ -408,6 +414,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/bot_token",
"crates/bots",
"crates/broadcast",
"crates/calendar_events",
@@ -521,6 +528,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/bot_token",
"crates/broadcast",
"crates/channel_sender",
"crates/cowlike",
@@ -592,6 +600,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/bot_token",
"crates/bots",
"crates/broadcast",
"crates/calendar_events",
@@ -706,6 +715,7 @@
"ai_usage": [
"crates/ai_usage",
"crates/bot_id",
+ "crates/bot_token",
"crates/cowlike",
"crates/macro_auth",
"crates/macro_authorization",
@@ -750,6 +760,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/bot_token",
"crates/broadcast",
"crates/calendar_events",
"crates/call",
@@ -870,6 +881,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/bot_token",
"crates/cowlike",
"crates/document_sub_type",
"crates/macro_auth",
@@ -896,6 +908,10 @@
"crates/cowlike",
"crates/workspace-hack"
],
+ "bot_token": [
+ "crates/bot_token",
+ "crates/workspace-hack"
+ ],
"bots": [
"crates/activity",
"crates/agent",
@@ -903,6 +919,7 @@
"crates/ai_usage",
"crates/attachment",
"crates/bot_id",
+ "crates/bot_token",
"crates/bots",
"crates/broadcast",
"crates/channel_sender",
@@ -974,6 +991,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/bot_token",
"crates/broadcast",
"crates/call",
"crates/channel_sender",
@@ -1053,6 +1071,7 @@
"calendar_events": [
"crates/ai_toolset",
"crates/bot_id",
+ "crates/bot_token",
"crates/broadcast",
"crates/calendar_events",
"crates/channel_sender",
@@ -1087,6 +1106,7 @@
"crates/ai_usage",
"crates/attachment",
"crates/bot_id",
+ "crates/bot_token",
"crates/broadcast",
"crates/call",
"crates/channel_sender",
@@ -1157,6 +1177,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/bot_token",
"crates/bots",
"crates/broadcast",
"crates/calendar_events",
@@ -1277,6 +1298,7 @@
"crates/ai_usage",
"crates/attachment",
"crates/bot_id",
+ "crates/bot_token",
"crates/broadcast",
"crates/channel_sender",
"crates/channels",
@@ -1330,6 +1352,7 @@
"crates/ai_usage",
"crates/attachment",
"crates/bot_id",
+ "crates/bot_token",
"crates/channel_sender",
"crates/chat",
"crates/cowlike",
@@ -1375,6 +1398,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/bot_token",
"crates/bots",
"crates/broadcast",
"crates/call",
@@ -1466,6 +1490,7 @@
"crates/ai_usage",
"crates/attachment",
"crates/bot_id",
+ "crates/bot_token",
"crates/broadcast",
"crates/channel_sender",
"crates/channels",
@@ -1523,6 +1548,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/bot_token",
"crates/broadcast",
"crates/call",
"crates/channel_sender",
@@ -1631,6 +1657,7 @@
"crates/ai_usage",
"crates/attachment",
"crates/bot_id",
+ "crates/bot_token",
"crates/connection",
"crates/connection_gateway_client",
"crates/connection_gateway_models",
@@ -1662,6 +1689,7 @@
"crates/ai_usage",
"crates/attachment",
"crates/bot_id",
+ "crates/bot_token",
"crates/connection_gateway_client",
"crates/connection_gateway_models",
"crates/cowlike",
@@ -1712,6 +1740,7 @@
],
"contacts": [
"crates/bot_id",
+ "crates/bot_token",
"crates/contacts",
"crates/cowlike",
"crates/macro_auth",
@@ -1732,6 +1761,7 @@
"crates/ai_usage",
"crates/attachment",
"crates/bot_id",
+ "crates/bot_token",
"crates/contacts",
"crates/cowlike",
"crates/database_env_vars",
@@ -1774,6 +1804,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/bot_token",
"crates/broadcast",
"crates/channel_sender",
"crates/cowlike",
@@ -1855,6 +1886,7 @@
"crates/ai_usage",
"crates/attachment",
"crates/bot_id",
+ "crates/bot_token",
"crates/broadcast",
"crates/channel_sender",
"crates/cowlike",
@@ -1941,6 +1973,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/bot_token",
"crates/broadcast",
"crates/call",
"crates/channel_sender",
@@ -2046,6 +2079,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/bot_token",
"crates/bots",
"crates/broadcast",
"crates/calendar_events",
@@ -2180,6 +2214,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/bot_token",
"crates/bots",
"crates/broadcast",
"crates/cal",
@@ -2324,6 +2359,7 @@
"crates/ai_usage",
"crates/attachment",
"crates/bot_id",
+ "crates/bot_token",
"crates/cowlike",
"crates/document_storage_service_client",
"crates/document_sub_type",
@@ -2355,6 +2391,7 @@
"crates/ai_usage",
"crates/attachment",
"crates/bot_id",
+ "crates/bot_token",
"crates/cowlike",
"crates/document_sub_type",
"crates/macro_auth",
@@ -2390,6 +2427,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/bot_token",
"crates/broadcast",
"crates/call",
"crates/channel_sender",
@@ -2478,6 +2516,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/bot_token",
"crates/broadcast",
"crates/call",
"crates/channel_sender",
@@ -2563,6 +2602,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/bot_token",
"crates/broadcast",
"crates/channel_sender",
"crates/cowlike",
@@ -2643,6 +2683,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/bot_token",
"crates/broadcast",
"crates/channel_sender",
"crates/cowlike",
@@ -2716,6 +2757,7 @@
"email_formatting": [
"crates/ai_toolset",
"crates/bot_id",
+ "crates/bot_token",
"crates/broadcast",
"crates/channel_sender",
"crates/cowlike",
@@ -2751,6 +2793,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/bot_token",
"crates/broadcast",
"crates/channel_sender",
"crates/cowlike",
@@ -2815,6 +2858,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/bot_token",
"crates/broadcast",
"crates/channel_sender",
"crates/cowlike",
@@ -2879,6 +2923,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/bot_token",
"crates/broadcast",
"crates/calendar_events",
"crates/channel_sender",
@@ -2966,6 +3011,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/bot_token",
"crates/broadcast",
"crates/channel_sender",
"crates/cowlike",
@@ -3024,6 +3070,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/bot_token",
"crates/broadcast",
"crates/channel_sender",
"crates/cowlike",
@@ -3086,6 +3133,7 @@
"crates/ai_usage",
"crates/attachment",
"crates/bot_id",
+ "crates/bot_token",
"crates/cowlike",
"crates/document_sub_type",
"crates/entity_access_db_utils",
@@ -3140,6 +3188,7 @@
"crates/ai_usage",
"crates/attachment",
"crates/bot_id",
+ "crates/bot_token",
"crates/cowlike",
"crates/document_sub_type",
"crates/entity_access",
@@ -3191,6 +3240,7 @@
"crates/ai_usage",
"crates/attachment",
"crates/bot_id",
+ "crates/bot_token",
"crates/cowlike",
"crates/document_sub_type",
"crates/entity_access",
@@ -3220,6 +3270,7 @@
"crates/ai_usage",
"crates/attachment",
"crates/bot_id",
+ "crates/bot_token",
"crates/cowlike",
"crates/document_sub_type",
"crates/entity_access",
@@ -3252,6 +3303,7 @@
"crates/ai_usage",
"crates/attachment",
"crates/bot_id",
+ "crates/bot_token",
"crates/cowlike",
"crates/document_sub_type",
"crates/entity_access",
@@ -3307,6 +3359,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/bot_token",
"crates/broadcast",
"crates/call",
"crates/channel_sender",
@@ -3400,6 +3453,7 @@
"crates/activity",
"crates/ai_toolset",
"crates/bot_id",
+ "crates/bot_token",
"crates/channel_sender",
"crates/cowlike",
"crates/document_sub_type",
@@ -3432,6 +3486,7 @@
"crates/ai_usage",
"crates/attachment",
"crates/bot_id",
+ "crates/bot_token",
"crates/broadcast",
"crates/channel_sender",
"crates/channels",
@@ -3483,6 +3538,7 @@
],
"graphql_common": [
"crates/bot_id",
+ "crates/bot_token",
"crates/cowlike",
"crates/document_sub_type",
"crates/filter_ast",
@@ -3510,6 +3566,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/bot_token",
"crates/broadcast",
"crates/channel_sender",
"crates/cowlike",
@@ -3570,6 +3627,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/bot_token",
"crates/broadcast",
"crates/call",
"crates/channel_sender",
@@ -3671,6 +3729,7 @@
"crates/ai_usage",
"crates/attachment",
"crates/bot_id",
+ "crates/bot_token",
"crates/cowlike",
"crates/document_sub_type",
"crates/entity_access",
@@ -3698,6 +3757,7 @@
"graphql_notification": [
"crates/ai_toolset",
"crates/bot_id",
+ "crates/bot_token",
"crates/broadcast",
"crates/channel_sender",
"crates/cowlike",
@@ -3738,6 +3798,7 @@
"crates/ai_usage",
"crates/attachment",
"crates/bot_id",
+ "crates/bot_token",
"crates/cowlike",
"crates/document_sub_type",
"crates/entity_access",
@@ -3768,6 +3829,7 @@
"crates/ai_usage",
"crates/attachment",
"crates/bot_id",
+ "crates/bot_token",
"crates/broadcast",
"crates/channel_sender",
"crates/cowlike",
@@ -3821,6 +3883,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/bot_token",
"crates/broadcast",
"crates/call",
"crates/channel_sender",
@@ -3917,6 +3980,7 @@
],
"graphql_soup_filter_input": [
"crates/bot_id",
+ "crates/bot_token",
"crates/cowlike",
"crates/document_sub_type",
"crates/filter_ast",
@@ -3951,6 +4015,7 @@
"crates/ai_usage",
"crates/attachment",
"crates/bot_id",
+ "crates/bot_token",
"crates/cowlike",
"crates/document_sub_type",
"crates/entity_access_db_utils",
@@ -3997,6 +4062,7 @@
"crates/ai_usage",
"crates/attachment",
"crates/bot_id",
+ "crates/bot_token",
"crates/broadcast",
"crates/channel_sender",
"crates/connection_gateway_client",
@@ -4045,6 +4111,7 @@
"invite_email": [
"crates/ai_toolset",
"crates/bot_id",
+ "crates/bot_token",
"crates/broadcast",
"crates/cowlike",
"crates/invite_email",
@@ -4118,6 +4185,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/bot_token",
"crates/broadcast",
"crates/call",
"crates/channel_sender",
@@ -4193,6 +4261,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/bot_token",
"crates/broadcast",
"crates/call",
"crates/channel_sender",
@@ -4293,6 +4362,7 @@
],
"macro_authorization": [
"crates/bot_id",
+ "crates/bot_token",
"crates/cowlike",
"crates/macro_auth",
"crates/macro_authorization",
@@ -4341,6 +4411,7 @@
"crates/ai_usage",
"crates/attachment",
"crates/bot_id",
+ "crates/bot_token",
"crates/cowlike",
"crates/document_sub_type",
"crates/entity_access_db_utils",
@@ -4408,6 +4479,7 @@
"crates/ai_usage",
"crates/attachment",
"crates/bot_id",
+ "crates/bot_token",
"crates/cowlike",
"crates/document_sub_type",
"crates/entity_access_db_utils",
@@ -4462,6 +4534,7 @@
"crates/ai_usage",
"crates/attachment",
"crates/bot_id",
+ "crates/bot_token",
"crates/cowlike",
"crates/document_sub_type",
"crates/macro_auth",
@@ -4518,6 +4591,7 @@
"crates/ai_usage",
"crates/attachment",
"crates/bot_id",
+ "crates/bot_token",
"crates/cowlike",
"crates/macro_auth",
"crates/macro_authorization",
@@ -4541,6 +4615,7 @@
"crates/ai_usage",
"crates/attachment",
"crates/bot_id",
+ "crates/bot_token",
"crates/cowlike",
"crates/macro_auth",
"crates/macro_authorization",
@@ -4573,6 +4648,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/bot_token",
"crates/bots",
"crates/broadcast",
"crates/calendar_events",
@@ -4697,6 +4773,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/bot_token",
"crates/bots",
"crates/broadcast",
"crates/calendar_events",
@@ -4825,6 +4902,7 @@
"crates/ai_usage",
"crates/attachment",
"crates/bot_id",
+ "crates/bot_token",
"crates/cowlike",
"crates/document_sub_type",
"crates/macro_auth",
@@ -4861,6 +4939,7 @@
"model_notifications": [
"crates/ai_toolset",
"crates/bot_id",
+ "crates/bot_token",
"crates/broadcast",
"crates/channel_sender",
"crates/cowlike",
@@ -4949,6 +5028,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/bot_token",
"crates/broadcast",
"crates/call",
"crates/channel_sender",
@@ -5029,6 +5109,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/bot_token",
"crates/broadcast",
"crates/call",
"crates/channel_sender",
@@ -5099,6 +5180,7 @@
"crates/ai_usage",
"crates/attachment",
"crates/bot_id",
+ "crates/bot_token",
"crates/broadcast",
"crates/channel_sender",
"crates/channels",
@@ -5165,6 +5247,7 @@
"notification": [
"crates/ai_toolset",
"crates/bot_id",
+ "crates/bot_token",
"crates/broadcast",
"crates/cowlike",
"crates/kafka_util",
@@ -5190,6 +5273,7 @@
"notification_db_client": [
"crates/ai_toolset",
"crates/bot_id",
+ "crates/bot_token",
"crates/broadcast",
"crates/channel_sender",
"crates/cowlike",
@@ -5220,6 +5304,7 @@
"notification_sandbox": [
"crates/ai_toolset",
"crates/bot_id",
+ "crates/bot_token",
"crates/broadcast",
"crates/channel_sender",
"crates/cowlike",
@@ -5255,6 +5340,7 @@
"crates/ai_usage",
"crates/attachment",
"crates/bot_id",
+ "crates/bot_token",
"crates/broadcast",
"crates/channel_sender",
"crates/cowlike",
@@ -5319,6 +5405,7 @@
"crates/ai_usage",
"crates/attachment",
"crates/bot_id",
+ "crates/bot_token",
"crates/broadcast",
"crates/channel_sender",
"crates/connection_gateway_client",
@@ -5385,6 +5472,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/bot_token",
"crates/broadcast",
"crates/channel_sender",
"crates/cowlike",
@@ -5449,6 +5537,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/bot_token",
"crates/broadcast",
"crates/channel_sender",
"crates/cowlike",
@@ -5508,6 +5597,7 @@
"pipedream_mcp": [
"crates/ai_toolset",
"crates/bot_id",
+ "crates/bot_token",
"crates/cowlike",
"crates/macro_auth",
"crates/macro_authorization",
@@ -5533,6 +5623,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/bot_token",
"crates/broadcast",
"crates/call",
"crates/channel_sender",
@@ -5627,6 +5718,7 @@
"crates/ai_usage",
"crates/attachment",
"crates/bot_id",
+ "crates/bot_token",
"crates/broadcast",
"crates/channel_sender",
"crates/cowlike",
@@ -5673,6 +5765,7 @@
"crates/ai_usage",
"crates/attachment",
"crates/bot_id",
+ "crates/bot_token",
"crates/broadcast",
"crates/channel_sender",
"crates/cowlike",
@@ -5724,6 +5817,7 @@
"referral": [
"crates/ai_toolset",
"crates/bot_id",
+ "crates/bot_token",
"crates/broadcast",
"crates/cowlike",
"crates/invite_email",
@@ -5755,6 +5849,7 @@
"crates/ai_usage",
"crates/attachment",
"crates/bot_id",
+ "crates/bot_token",
"crates/broadcast",
"crates/channel_sender",
"crates/cowlike",
@@ -5829,6 +5924,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/bot_token",
"crates/bots",
"crates/broadcast",
"crates/calendar_events",
@@ -5950,6 +6046,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/bot_token",
"crates/broadcast",
"crates/call",
"crates/channel_sender",
@@ -6058,6 +6155,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/bot_token",
"crates/broadcast",
"crates/call",
"crates/channel_sender",
@@ -6141,6 +6239,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/bot_token",
"crates/broadcast",
"crates/call",
"crates/channel_sender",
@@ -6212,6 +6311,7 @@
"crates/ai_usage",
"crates/attachment",
"crates/bot_id",
+ "crates/bot_token",
"crates/cowlike",
"crates/document_storage_service_client",
"crates/document_sub_type",
@@ -6255,6 +6355,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/bot_token",
"crates/broadcast",
"crates/call",
"crates/channel_sender",
@@ -6371,6 +6472,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/bot_token",
"crates/broadcast",
"crates/call",
"crates/channel_sender",
@@ -6454,6 +6556,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/bot_token",
"crates/broadcast",
"crates/call",
"crates/channel_sender",
@@ -6525,6 +6628,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/bot_token",
"crates/broadcast",
"crates/call",
"crates/channel_sender",
@@ -6600,6 +6704,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/bot_token",
"crates/broadcast",
"crates/call",
"crates/channel_sender",
@@ -6672,6 +6777,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/bot_token",
"crates/broadcast",
"crates/call",
"crates/channel_sender",
@@ -6766,6 +6872,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/bot_token",
"crates/broadcast",
"crates/channel_sender",
"crates/cowlike",
@@ -6838,6 +6945,7 @@
"crates/ai_usage",
"crates/attachment",
"crates/bot_id",
+ "crates/bot_token",
"crates/cowlike",
"crates/document_sub_type",
"crates/macro_auth",
@@ -6896,6 +7004,7 @@
"crates/ai_usage",
"crates/attachment",
"crates/bot_id",
+ "crates/bot_token",
"crates/cowlike",
"crates/document_sub_type",
"crates/macro_auth",
@@ -6921,6 +7030,7 @@
],
"sync_service_hex": [
"crates/bot_id",
+ "crates/bot_token",
"crates/cowlike",
"crates/macro_auth",
"crates/macro_authorization",
@@ -6957,6 +7067,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/bot_token",
"crates/broadcast",
"crates/call",
"crates/channel_sender",
@@ -7035,6 +7146,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/bot_token",
"crates/broadcast",
"crates/channel_sender",
"crates/channels",
@@ -7123,6 +7235,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/bot_token",
"crates/broadcast",
"crates/channel_sender",
"crates/connection_gateway_client",
@@ -7190,6 +7303,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/bot_token",
"crates/broadcast",
"crates/channel_sender",
"crates/cowlike",
@@ -7253,6 +7367,7 @@
"crates/ai_usage",
"crates/attachment",
"crates/bot_id",
+ "crates/bot_token",
"crates/cowlike",
"crates/document_sub_type",
"crates/entity_access_db_utils",
@@ -7301,6 +7416,7 @@
"crates/attachment",
"crates/authentication_service_client",
"crates/bot_id",
+ "crates/bot_token",
"crates/bots",
"crates/broadcast",
"crates/call",
diff --git a/.sqlx/query-e6fcaa97f031c1da3526c816ee88e1abb3cf466142b51d7ed3838b5ea8a5b46e.json b/.sqlx/query-33d640ec17b5f3daff76c169a999c7347151ce6a8bed1faa103c27a490a110d6.json
similarity index 72%
rename from .sqlx/query-e6fcaa97f031c1da3526c816ee88e1abb3cf466142b51d7ed3838b5ea8a5b46e.json
rename to .sqlx/query-33d640ec17b5f3daff76c169a999c7347151ce6a8bed1faa103c27a490a110d6.json
index e6ee19200f..08cef514e3 100644
--- a/.sqlx/query-e6fcaa97f031c1da3526c816ee88e1abb3cf466142b51d7ed3838b5ea8a5b46e.json
+++ b/.sqlx/query-33d640ec17b5f3daff76c169a999c7347151ce6a8bed1faa103c27a490a110d6.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT id, bot_id, token, label, last_used_at, expires_at, revoked_at, created_at\n FROM bot_tokens\n WHERE bot_id = $1\n AND revoked_at IS NULL\n ORDER BY created_at DESC, id DESC\n ",
+ "query": "\n SELECT id, bot_id, token_prefix, label, last_used_at, expires_at, revoked_at, created_at\n FROM bot_tokens\n WHERE bot_id = $1\n AND revoked_at IS NULL\n ORDER BY created_at DESC, id DESC\n ",
"describe": {
"columns": [
{
@@ -15,7 +15,7 @@
},
{
"ordinal": 2,
- "name": "token",
+ "name": "token_prefix",
"type_info": "Text"
},
{
@@ -60,5 +60,5 @@
false
]
},
- "hash": "e6fcaa97f031c1da3526c816ee88e1abb3cf466142b51d7ed3838b5ea8a5b46e"
+ "hash": "33d640ec17b5f3daff76c169a999c7347151ce6a8bed1faa103c27a490a110d6"
}
diff --git a/.sqlx/query-d4e9676fcb9d7860e0e1f4c54bdc059688c703c58cbdc865b4c9bf25e9ddf354.json b/.sqlx/query-584398bb57affbb8adcaa431416ac2564922f6f3ef51a005404a6d69f97146e1.json
similarity index 68%
rename from .sqlx/query-d4e9676fcb9d7860e0e1f4c54bdc059688c703c58cbdc865b4c9bf25e9ddf354.json
rename to .sqlx/query-584398bb57affbb8adcaa431416ac2564922f6f3ef51a005404a6d69f97146e1.json
index e209218fea..546d5281b2 100644
--- a/.sqlx/query-d4e9676fcb9d7860e0e1f4c54bdc059688c703c58cbdc865b4c9bf25e9ddf354.json
+++ b/.sqlx/query-584398bb57affbb8adcaa431416ac2564922f6f3ef51a005404a6d69f97146e1.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT\n bt.id AS token_id,\n bt.bot_id,\n bt.token,\n bt.label,\n bt.last_used_at,\n bt.expires_at,\n bt.revoked_at,\n bt.created_at,\n b.kind\n FROM bot_tokens bt\n JOIN bots b ON b.id = bt.bot_id\n WHERE bt.token = $1\n AND b.deleted_at IS NULL\n ",
+ "query": "\n SELECT\n bt.id AS token_id,\n bt.bot_id,\n bt.token_prefix,\n bt.label,\n bt.last_used_at,\n bt.expires_at,\n bt.revoked_at,\n bt.created_at,\n b.kind\n FROM bot_tokens bt\n JOIN bots b ON b.id = bt.bot_id\n WHERE bt.token_hash = $1\n AND b.deleted_at IS NULL\n ",
"describe": {
"columns": [
{
@@ -15,7 +15,7 @@
},
{
"ordinal": 2,
- "name": "token",
+ "name": "token_prefix",
"type_info": "Text"
},
{
@@ -51,7 +51,7 @@
],
"parameters": {
"Left": [
- "Text"
+ "Bytea"
]
},
"nullable": [
@@ -66,5 +66,5 @@
false
]
},
- "hash": "d4e9676fcb9d7860e0e1f4c54bdc059688c703c58cbdc865b4c9bf25e9ddf354"
+ "hash": "584398bb57affbb8adcaa431416ac2564922f6f3ef51a005404a6d69f97146e1"
}
diff --git a/.sqlx/query-13ca7c91a890393503f054cd200c45ae96ad56d3c48b4ee20b207c9bfa4bbc9f.json b/.sqlx/query-731fe962bc2376292a2c6ab2dbbb6ea1500ea4a8e3222fb8a60c47fb8e88a89e.json
similarity index 62%
rename from .sqlx/query-13ca7c91a890393503f054cd200c45ae96ad56d3c48b4ee20b207c9bfa4bbc9f.json
rename to .sqlx/query-731fe962bc2376292a2c6ab2dbbb6ea1500ea4a8e3222fb8a60c47fb8e88a89e.json
index a6b29ad9aa..24565c2680 100644
--- a/.sqlx/query-13ca7c91a890393503f054cd200c45ae96ad56d3c48b4ee20b207c9bfa4bbc9f.json
+++ b/.sqlx/query-731fe962bc2376292a2c6ab2dbbb6ea1500ea4a8e3222fb8a60c47fb8e88a89e.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT\n bt.id AS token_id,\n bt.bot_id,\n bt.token,\n bt.label,\n bt.last_used_at,\n bt.expires_at,\n bt.revoked_at,\n bt.created_at,\n b.kind\n FROM bot_tokens bt\n JOIN bots b ON b.id = bt.bot_id\n JOIN comms_channel_participants cp\n ON cp.channel_id = $1\n AND cp.user_id = ('bot|' || b.id::text)\n AND cp.left_at IS NULL\n WHERE bt.token = $2\n AND b.deleted_at IS NULL\n ",
+ "query": "\n SELECT\n bt.id AS token_id,\n bt.bot_id,\n bt.token_prefix,\n bt.label,\n bt.last_used_at,\n bt.expires_at,\n bt.revoked_at,\n bt.created_at,\n b.kind\n FROM bot_tokens bt\n JOIN bots b ON b.id = bt.bot_id\n JOIN comms_channel_participants cp\n ON cp.channel_id = $1\n AND cp.user_id = ('bot|' || b.id::text)\n AND cp.left_at IS NULL\n WHERE bt.token_hash = $2\n AND b.deleted_at IS NULL\n ",
"describe": {
"columns": [
{
@@ -15,7 +15,7 @@
},
{
"ordinal": 2,
- "name": "token",
+ "name": "token_prefix",
"type_info": "Text"
},
{
@@ -52,7 +52,7 @@
"parameters": {
"Left": [
"Uuid",
- "Text"
+ "Bytea"
]
},
"nullable": [
@@ -67,5 +67,5 @@
false
]
},
- "hash": "13ca7c91a890393503f054cd200c45ae96ad56d3c48b4ee20b207c9bfa4bbc9f"
+ "hash": "731fe962bc2376292a2c6ab2dbbb6ea1500ea4a8e3222fb8a60c47fb8e88a89e"
}
diff --git a/.sqlx/query-856b67c520a563f550f1059b9ab0a32a7a97a24f6ce0925c6d2541381a0074d7.json b/.sqlx/query-856b67c520a563f550f1059b9ab0a32a7a97a24f6ce0925c6d2541381a0074d7.json
new file mode 100644
index 0000000000..8efe010549
--- /dev/null
+++ b/.sqlx/query-856b67c520a563f550f1059b9ab0a32a7a97a24f6ce0925c6d2541381a0074d7.json
@@ -0,0 +1,18 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n INSERT INTO bot_tokens (id, bot_id, token_hash, token_prefix, revoked_at)\n VALUES ($1, $2, $3, $4, CASE WHEN $5 THEN now() ELSE NULL END)\n ",
+ "describe": {
+ "columns": [],
+ "parameters": {
+ "Left": [
+ "Uuid",
+ "Uuid",
+ "Bytea",
+ "Text",
+ "Bool"
+ ]
+ },
+ "nullable": []
+ },
+ "hash": "856b67c520a563f550f1059b9ab0a32a7a97a24f6ce0925c6d2541381a0074d7"
+}
diff --git a/.sqlx/query-e50a704e19cd5a0e8bf252e30dba739875031e24d8735ca4a02e9ee39bddddff.json b/.sqlx/query-dcf19b1a30385a18a23d0fa7d4d724d755c0a3353480bcbe573a3f867cf24091.json
similarity index 75%
rename from .sqlx/query-e50a704e19cd5a0e8bf252e30dba739875031e24d8735ca4a02e9ee39bddddff.json
rename to .sqlx/query-dcf19b1a30385a18a23d0fa7d4d724d755c0a3353480bcbe573a3f867cf24091.json
index affe276cc0..15e39a719d 100644
--- a/.sqlx/query-e50a704e19cd5a0e8bf252e30dba739875031e24d8735ca4a02e9ee39bddddff.json
+++ b/.sqlx/query-dcf19b1a30385a18a23d0fa7d4d724d755c0a3353480bcbe573a3f867cf24091.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n INSERT INTO bot_tokens (\n id, bot_id, token, label, expires_at\n )\n VALUES ($1, $2, $3, $4, $5)\n RETURNING id, bot_id, token, label, last_used_at, expires_at, revoked_at, created_at\n ",
+ "query": "\n INSERT INTO bot_tokens (\n id, bot_id, token_hash, token_prefix, label, expires_at\n )\n VALUES ($1, $2, $3, $4, $5, $6)\n RETURNING id, bot_id, token_prefix, label, last_used_at, expires_at, revoked_at, created_at\n ",
"describe": {
"columns": [
{
@@ -15,7 +15,7 @@
},
{
"ordinal": 2,
- "name": "token",
+ "name": "token_prefix",
"type_info": "Text"
},
{
@@ -48,6 +48,7 @@
"Left": [
"Uuid",
"Uuid",
+ "Bytea",
"Text",
"Text",
"Timestamptz"
@@ -64,5 +65,5 @@
false
]
},
- "hash": "e50a704e19cd5a0e8bf252e30dba739875031e24d8735ca4a02e9ee39bddddff"
+ "hash": "dcf19b1a30385a18a23d0fa7d4d724d755c0a3353480bcbe573a3f867cf24091"
}
diff --git a/.sqlx/query-eb3db180aff5d16f1eed86bfbddf2ffbe4cec0122e364242dec6fec10a98c1c8.json b/.sqlx/query-e0946fb090947f744277ff91e170617be8aed2673e1468589afa64f80c838f4e.json
similarity index 75%
rename from .sqlx/query-eb3db180aff5d16f1eed86bfbddf2ffbe4cec0122e364242dec6fec10a98c1c8.json
rename to .sqlx/query-e0946fb090947f744277ff91e170617be8aed2673e1468589afa64f80c838f4e.json
index 07ddddb5f3..bdcc42e1ef 100644
--- a/.sqlx/query-eb3db180aff5d16f1eed86bfbddf2ffbe4cec0122e364242dec6fec10a98c1c8.json
+++ b/.sqlx/query-e0946fb090947f744277ff91e170617be8aed2673e1468589afa64f80c838f4e.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n SELECT\n bt.id AS token_id,\n b.id AS bot_id,\n b.kind,\n b.owner_user_id,\n b.team_id\n FROM bot_tokens bt\n JOIN bots b ON b.id = bt.bot_id\n WHERE bt.token = $1\n AND bt.revoked_at IS NULL\n AND (bt.expires_at IS NULL OR bt.expires_at > now())\n AND b.deleted_at IS NULL\n ",
+ "query": "\n SELECT\n bt.id AS token_id,\n b.id AS bot_id,\n b.kind,\n b.owner_user_id,\n b.team_id\n FROM bot_tokens bt\n JOIN bots b ON b.id = bt.bot_id\n WHERE bt.token_hash = $1\n AND bt.revoked_at IS NULL\n AND (bt.expires_at IS NULL OR bt.expires_at > now())\n AND b.deleted_at IS NULL\n ",
"describe": {
"columns": [
{
@@ -31,7 +31,7 @@
],
"parameters": {
"Left": [
- "Text"
+ "Bytea"
]
},
"nullable": [
@@ -42,5 +42,5 @@
true
]
},
- "hash": "eb3db180aff5d16f1eed86bfbddf2ffbe4cec0122e364242dec6fec10a98c1c8"
+ "hash": "e0946fb090947f744277ff91e170617be8aed2673e1468589afa64f80c838f4e"
}
diff --git a/.sqlx/query-f07c7c14b06831f213fd48fd34dcb05b3fae3ced5e464d75cab227bcc4db6835.json b/.sqlx/query-f07c7c14b06831f213fd48fd34dcb05b3fae3ced5e464d75cab227bcc4db6835.json
new file mode 100644
index 0000000000..f55b5927f0
--- /dev/null
+++ b/.sqlx/query-f07c7c14b06831f213fd48fd34dcb05b3fae3ced5e464d75cab227bcc4db6835.json
@@ -0,0 +1,22 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "SELECT digest(convert_to($1, 'UTF8'), 'sha256')",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "digest",
+ "type_info": "Bytea"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text"
+ ]
+ },
+ "nullable": [
+ null
+ ]
+ },
+ "hash": "f07c7c14b06831f213fd48fd34dcb05b3fae3ced5e464d75cab227bcc4db6835"
+}
diff --git a/Cargo.lock b/Cargo.lock
index e647eae34f..0a1f18d24d 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2646,6 +2646,14 @@ dependencies = [
"workspace-hack",
]
+[[package]]
+name = "bot_token"
+version = "0.1.0"
+dependencies = [
+ "sha2 0.10.9",
+ "workspace-hack",
+]
+
[[package]]
name = "bots"
version = "0.1.0"
@@ -2655,6 +2663,7 @@ dependencies = [
"async-trait",
"axum",
"bot_id",
+ "bot_token",
"channels",
"chrono",
"entity_access",
@@ -8894,6 +8903,7 @@ name = "local_e2e_integration_tests"
version = "0.1.0"
dependencies = [
"anyhow",
+ "bot_token",
"futures",
"local_e2e_test_support",
"reqwest 0.13.4",
@@ -9206,6 +9216,7 @@ version = "0.1.0"
dependencies = [
"axum",
"bot_id",
+ "bot_token",
"constant_time_eq",
"cookie",
"http-body-util",
diff --git a/Cargo.toml b/Cargo.toml
index 05c4b4c5bd..ff421905d5 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -10,6 +10,7 @@ members = [
"crates/ai_projections",
"crates/ai_usage",
"crates/bot_id",
+ "crates/bot_token",
"crates/bots",
"crates/broadcast",
"crates/calendar_events",
diff --git a/apps/docs/AI/mcp/tools/create-bot.mdx b/apps/docs/AI/mcp/tools/create-bot.mdx
index 2085231e72..19c2fb41cc 100644
--- a/apps/docs/AI/mcp/tools/create-bot.mdx
+++ b/apps/docs/AI/mcp/tools/create-bot.mdx
@@ -1,11 +1,11 @@
---
title: CreateBot
-description: "Create a bot with a name, stable handle, and optional profile. Omit teamId for a bot owned by the current user; provide teamId to create a team-owned bot, which requires team administrator or owner permission. Pass channelId when the bot should post to a channel immediately: the current user must be a member of that channel. The response then includes a one-time bearerToken and that channel's webhook URL. Omit channelId to create the bot only, then use ManageBotChannelAccess and IssueBotCredential for later setup."
+description: "Create a bot with a name, stable handle, and optional profile. Omit teamId for a bot owned by the current user; provide teamId to create a team-owned bot, which requires team administrator or owner permission. Pass channelId when the bot should post to a channel immediately: the current user must be a member of that channel. The response then includes that channel's webhook URL and a credential proposal. The user mints the bearer token from the chat card or bot settings; the secret is never returned in this tool result. Omit channelId to create the bot only, then use ManageBotChannelAccess and IssueBotCredential for later setup."
---
# CreateBot
-Create a bot with a name, stable handle, and optional profile. Omit teamId for a bot owned by the current user; provide teamId to create a team-owned bot, which requires team administrator or owner permission. Pass channelId when the bot should post to a channel immediately: the current user must be a member of that channel. The response then includes a one-time bearerToken and that channel's webhook URL. Omit channelId to create the bot only, then use ManageBotChannelAccess and IssueBotCredential for later setup.
+Create a bot with a name, stable handle, and optional profile. Omit teamId for a bot owned by the current user; provide teamId to create a team-owned bot, which requires team administrator or owner permission. Pass channelId when the bot should post to a channel immediately: the current user must be a member of that channel. The response then includes that channel's webhook URL and a credential proposal. The user mints the bearer token from the chat card or bot settings; the secret is never returned in this tool result. Omit channelId to create the bot only, then use ManageBotChannelAccess and IssueBotCredential for later setup.
## Parameters
@@ -16,7 +16,7 @@ Create a bot with a name, stable handle, and optional profile. Omit teamId for a
| `handle` | string | Yes | Stable mention handle using only lowercase ASCII letters, digits, hyphens, and underscores; maximum 64 characters. |
| `description` | string | No | Optional short description of what the bot does. |
| `avatarUrl` | string | No | Optional URL for the bot profile picture. Pass the URL of an image already uploaded to Macro static files or another reachable image URL. |
-| `channelId` | string | No | Channel id to grant the new bot access to. Requires current-user channel membership. When set, the tool also mints a credential and returns the channel webhook URL. |
-| `credentialLabel` | string | No | Optional label for the credential minted when channelId is set, such as `github-webhook`. Requires channelId. |
-| `credentialExpiresAt` | string | No | Optional RFC 3339 expiration for the credential minted when channelId is set. Requires channelId. |
+| `channelId` | string | No | Channel id to grant the new bot access to. Requires current-user channel membership. When set, the tool also returns the channel webhook URL and a credential proposal the user can mint from the chat card. |
+| `credentialLabel` | string | No | Optional label for the credential the user will mint when channelId is set, such as `github-webhook`. Requires channelId. |
+| `credentialExpiresAt` | string | No | Optional RFC 3339 expiration for the credential the user will mint when channelId is set. Requires channelId. |
| `hasAgent` | boolean | No | Set true if mentioning this bot should open a sandboxed coding-agent session. Defaults to false. |
diff --git a/apps/docs/AI/mcp/tools/get-bot-webhooks.mdx b/apps/docs/AI/mcp/tools/get-bot-webhooks.mdx
index e990de1d1b..1de4f014f4 100644
--- a/apps/docs/AI/mcp/tools/get-bot-webhooks.mdx
+++ b/apps/docs/AI/mcp/tools/get-bot-webhooks.mdx
@@ -1,11 +1,11 @@
---
title: GetBotWebhooks
-description: "Get the channel-specific webhook URLs for a bot the current user can manage. A bot has one URL per channel it can access. POST message content to a returned webhookUrl and authenticate with a token from IssueBotCredential or CreateBot in the returned credentialHeader; also send credentialScope in credentialScopeHeader. If no URLs are returned, add the bot to a channel with ManageBotChannelAccess or recreate it with CreateBot and channelId."
+description: "Get the channel-specific webhook URLs for a bot the current user can manage. A bot has one URL per channel it can access. POST message content to a returned webhookUrl and authenticate with a token minted from the chat card or bot settings after IssueBotCredential or CreateBot; send it in the returned credentialHeader and send credentialScope in credentialScopeHeader. If no URLs are returned, add the bot to a channel with ManageBotChannelAccess or recreate it with CreateBot and channelId."
---
# GetBotWebhooks
-Get the channel-specific webhook URLs for a bot the current user can manage. A bot has one URL per channel it can access. POST message content to a returned webhookUrl and authenticate with a token from IssueBotCredential or CreateBot in the returned credentialHeader; also send credentialScope in credentialScopeHeader. If no URLs are returned, add the bot to a channel with ManageBotChannelAccess or recreate it with CreateBot and channelId.
+Get the channel-specific webhook URLs for a bot the current user can manage. A bot has one URL per channel it can access. POST message content to a returned webhookUrl and authenticate with a token minted from the chat card or bot settings after IssueBotCredential or CreateBot; send it in the returned credentialHeader and send credentialScope in credentialScopeHeader. If no URLs are returned, add the bot to a channel with ManageBotChannelAccess or recreate it with CreateBot and channelId.
## Parameters
diff --git a/apps/docs/AI/mcp/tools/issue-bot-credential.mdx b/apps/docs/AI/mcp/tools/issue-bot-credential.mdx
index ced23ab9d4..b4176b21db 100644
--- a/apps/docs/AI/mcp/tools/issue-bot-credential.mdx
+++ b/apps/docs/AI/mcp/tools/issue-bot-credential.mdx
@@ -1,11 +1,11 @@
---
title: IssueBotCredential
-description: "Mint a new secret bearer token for a bot the current user can manage. Use this when the user asks for bot credentials or a webhook token; existing raw secrets cannot be recovered safely. The response contains a newly issued bearerToken and tokenId. Treat bearerToken as sensitive and tell the user to store it securely because it is shown only once."
+description: "Prepare a new bot credential for a bot the current user can manage. This does not mint the secret. Tell the user to click the chat card or open bot settings to create the token. The secret is shown only while that card is open. Use this when the user asks for bot credentials or a webhook token; existing raw secrets cannot be recovered safely."
---
# IssueBotCredential
-Mint a new secret bearer token for a bot the current user can manage. Use this when the user asks for bot credentials or a webhook token; existing raw secrets cannot be recovered safely. The response contains a newly issued bearerToken and tokenId. Treat bearerToken as sensitive and tell the user to store it securely because it is shown only once.
+Prepare a new bot credential for a bot the current user can manage. This does not mint the secret. Tell the user to click the chat card or open bot settings to create the token. The secret is shown only while that card is open. Use this when the user asks for bot credentials or a webhook token; existing raw secrets cannot be recovered safely.
## Parameters
diff --git a/apps/web/src/features/channel/Bots/CreateBotTokenDialog.tsx b/apps/web/src/features/channel/Bots/CreateBotTokenDialog.tsx
index 54a24fdab8..a0ad67a0d1 100644
--- a/apps/web/src/features/channel/Bots/CreateBotTokenDialog.tsx
+++ b/apps/web/src/features/channel/Bots/CreateBotTokenDialog.tsx
@@ -1,52 +1,35 @@
-import { toast } from '@core/component/Toast/Toast';
import KeyIcon from '@phosphor/key.svg';
import XIcon from '@phosphor/x.svg';
-import { useCreateBotTokenMutation } from '@queries/bots/bots';
import type { Bot } from '@service-storage/generated/schemas/bot';
import { Button, Dialog, Panel } from '@ui';
import { createSignal, Show } from 'solid-js';
import { BotAvatar } from './BotAvatar';
-import { CredentialField } from './CredentialField';
+import { MintCredential, useMintBotToken } from './MintCredential';
export function CreateBotTokenDialog(props: {
open: boolean;
onOpenChange: (open: boolean) => void;
bot?: Bot;
}) {
- const createTokenMutation = useCreateBotTokenMutation();
+ const minted = useMintBotToken();
const [label, setLabel] = createSignal('webhook');
- const [token, setToken] = createSignal<string>();
const reset = () => {
setLabel('webhook');
- setToken(undefined);
+ minted.reset();
};
const close = () => {
- if (createTokenMutation.isPending) return;
+ if (minted.isPending()) return;
props.onOpenChange(false);
reset();
};
- const create = () => {
- const bot = props.bot;
- if (!bot) return;
- createTokenMutation.mutate(
- { botId: bot.id, label: label().trim() || undefined },
- {
- onSuccess: ({ bearer_token }) => setToken(bearer_token),
- onError: () => toast.failure('Failed to create token'),
- }
- );
- };
-
return (
<Dialog
open={props.open}
onOpenChange={(open) => (open ? props.onOpenChange(true) : close())}
- onEscapeKeyDown={(event) =>
- createTokenMutation.isPending && event.preventDefault()
- }
+ onEscapeKeyDown={(event) => minted.isPending() && event.preventDefault()}
position="center"
class="w-105"
>
@@ -61,7 +44,7 @@ export function CreateBotTokenDialog(props: {
size="icon-sm"
label="Close"
aria-label="Close"
- disabled={createTokenMutation.isPending}
+ disabled={minted.isPending()}
onClick={close}
>
<XIcon />
@@ -83,9 +66,13 @@ export function CreateBotTokenDialog(props: {
<KeyIcon class="size-5 text-ink-extra-muted" />
</div>
- <Show
- when={token()}
- fallback={
+ <MintCredential
+ minted={minted}
+ botId={bot().id}
+ label={label().trim() || undefined}
+ fieldLabel="Webhook token"
+ fieldHelp="Shown only once"
+ fallback={({ mint, isPending }) => (
<>
<label class="flex flex-col gap-1.5">
<span class="text-xs font-medium text-ink">
@@ -100,7 +87,7 @@ export function CreateBotTokenDialog(props: {
setLabel(event.currentTarget.value)
}
onKeyDown={(event) => {
- if (event.key === 'Enter') create();
+ if (event.key === 'Enter') mint();
}}
/>
<span class="text-xs text-ink-muted">
@@ -114,24 +101,16 @@ export function CreateBotTokenDialog(props: {
<Button
variant="cta"
size="sm"
- disabled={createTokenMutation.isPending}
- onClick={create}
+ disabled={isPending}
+ onClick={mint}
>
- {createTokenMutation.isPending
- ? 'Creating…'
- : 'Create token'}
+ {isPending ? 'Creating…' : 'Create token'}
</Button>
</div>
</>
- }
- >
- {(rawToken) => (
+ )}
+ afterToken={
<>
- <CredentialField
- label="Webhook token"
- value={rawToken()}
- help="Shown only once"
- />
<div class="rounded-lg border border-alert/30 bg-alert-bg px-3 py-2.5 text-xs text-alert-ink">
Store this token somewhere secure before closing.
</div>
@@ -141,8 +120,8 @@ export function CreateBotTokenDialog(props: {
</Button>
</div>
</>
- )}
- </Show>
+ }
+ />
</div>
)}
</Show>
diff --git a/apps/web/src/features/channel/Bots/MintCredential.tsx b/apps/web/src/features/channel/Bots/MintCredential.tsx
new file mode 100644
index 0000000000..d377989025
--- /dev/null
+++ b/apps/web/src/features/channel/Bots/MintCredential.tsx
@@ -0,0 +1,90 @@
+import { toast } from '@core/component/Toast/Toast';
+import { useCreateBotTokenMutation } from '@queries/bots/bots';
+import { Button } from '@ui';
+import { createSignal, type JSX, Show } from 'solid-js';
+import { CredentialField } from './CredentialField';
+
+export function useMintBotToken() {
+ const createToken = useCreateBotTokenMutation();
+ const [token, setToken] = createSignal<string>();
+
+ const mint = (vars: {
+ botId: string;
+ label?: string;
+ expiresAt?: string;
+ }) => {
+ if (createToken.isPending) return;
+ createToken.mutate(vars, {
+ onSuccess: ({ bearer_token }) => setToken(bearer_token),
+ onError: () => toast.failure('Failed to create token'),
+ });
+ };
+
+ return {
+ token,
+ mint,
+ isPending: () => createToken.isPending,
+ reset: () => setToken(undefined),
+ };
+}
+
+export function MintCredential(props: {
+ minted?: ReturnType<typeof useMintBotToken>;
+ botId: string;
+ label?: string | null;
+ expiresAt?: string | null;
+ fieldLabel?: string;
+ fieldHelp?: string;
+ description?: string;
+ fallback?: (api: { mint: () => void; isPending: boolean }) => JSX.Element;
+ afterToken?: JSX.Element;
+}) {
+ const minted = props.minted ?? useMintBotToken();
+ const mint = () =>
+ minted.mint({
+ botId: props.botId,
+ label: props.label ?? undefined,
+ expiresAt: props.expiresAt ?? undefined,
+ });
+
+ return (
+ <Show
+ when={minted.token()}
+ fallback={
+ props.fallback?.({ mint, isPending: minted.isPending() }) ?? (
+ <div class="flex flex-col gap-2">
+ <p class="text-xs text-ink-muted">
+ {props.description ??
+ 'Create a token to authenticate this bot. It is shown only while this card is open. You can mint a new one anytime from bot settings.'}
+ </p>
+ <div>
+ <Button
+ type="button"
+ variant="cta"
+ size="sm"
+ disabled={minted.isPending()}
+ onClick={mint}
+ >
+ {minted.isPending() ? 'Creating…' : 'Create token'}
+ </Button>
+ </div>
+ </div>
+ )
+ }
+ >
+ {(rawToken) => (
+ <div class="flex flex-col gap-5">
+ <CredentialField
+ label={props.fieldLabel ?? 'Bearer token'}
+ value={rawToken()}
+ help={
+ props.fieldHelp ??
+ 'Shown only while this card is open. You can mint a new one anytime.'
+ }
+ />
+ {props.afterToken}
+ </div>
+ )}
+ </Show>
+ );
+}
diff --git a/apps/web/src/lib/core/component/AI/component/tool/Bots.tsx b/apps/web/src/lib/core/component/AI/component/tool/Bots.tsx
index 214cc74d0e..8b168efd18 100644
--- a/apps/web/src/lib/core/component/AI/component/tool/Bots.tsx
+++ b/apps/web/src/lib/core/component/AI/component/tool/Bots.tsx
@@ -1,3 +1,4 @@
+import { MintCredential } from '@channel/Bots/MintCredential';
import Key from '@phosphor-icons/core/regular/key.svg';
import Link from '@phosphor-icons/core/regular/link.svg';
import List from '@phosphor-icons/core/regular/list.svg';
@@ -149,28 +150,30 @@ const createBotHandler = createToolRenderer({
/>
<Show when={setup()}>
{(channelSetup) => (
- <DetailPanel
- details={[
- {
- label: 'Bearer token',
- value: channelSetup().bearerToken,
- secret: true,
- },
- {
- label: 'Webhook',
- value: channelSetup().webhook.webhookUrl,
- secret: true,
- },
- {
- label: 'Channel ID',
- value: channelSetup().channelId,
- },
- {
- label: 'Token header',
- value: channelSetup().credentialHeader,
- },
- ]}
- />
+ <div class="flex flex-col gap-2">
+ <DetailPanel
+ details={[
+ {
+ label: 'Webhook',
+ value: channelSetup().webhook.webhookUrl,
+ secret: true,
+ },
+ {
+ label: 'Channel ID',
+ value: channelSetup().channelId,
+ },
+ {
+ label: 'Token header',
+ value: channelSetup().credentialHeader,
+ },
+ ]}
+ />
+ <MintCredential
+ botId={bot()!.botId}
+ label={channelSetup().credentialLabel}
+ expiresAt={channelSetup().credentialExpiresAt}
+ />
+ </div>
)}
</Show>
</div>
@@ -189,7 +192,7 @@ const createBotHandler = createToolRenderer({
status={
ctx.response
? setup()
- ? 'Created · credential'
+ ? 'Created · mint token'
: 'Created'
: undefined
}
@@ -213,23 +216,21 @@ const issueBotCredentialHandler = createToolRenderer({
type="call"
response={
expanded() && credential() ? (
- <DetailPanel
- summary={credential()!.summary}
- details={[
- {
- label: 'Bearer token',
- value: credential()!.bearerToken,
- secret: true,
- },
- {
- label: 'Credential ID',
- value: credential()!.tokenId,
- secret: true,
- },
- { label: 'Label', value: credential()!.label },
- { label: 'Expires', value: credential()!.expiresAt },
- ]}
- />
+ <div class="flex flex-col gap-2">
+ <DetailPanel
+ summary={credential()!.summary}
+ details={[
+ { label: 'Bot ID', value: credential()!.botId },
+ { label: 'Label', value: credential()!.label },
+ { label: 'Expires', value: credential()!.expiresAt },
+ ]}
+ />
+ <MintCredential
+ botId={credential()!.botId}
+ label={credential()!.label}
+ expiresAt={credential()!.expiresAt}
+ />
+ </div>
) : undefined
}
>
@@ -244,7 +245,7 @@ const issueBotCredentialHandler = createToolRenderer({
expanded={expanded()}
onToggle={() => setExpanded((value) => !value)}
showToggle={!!credential()}
- status={ctx.response ? 'Sensitive' : undefined}
+ status={ctx.response ? 'Mint token' : undefined}
/>
</div>
</BaseTool>
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts
index e1d9b8db8b..d8e387e0d1 100644
--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/schemas.ts
@@ -736,8 +736,6 @@ export const CreateBotResponse = z.object({
.union([
z.object({
channelId: z.string().uuid(),
- tokenId: z.string().uuid(),
- bearerToken: z.string(),
webhook: z.object({
channelId: z.string().uuid(),
channelName: z.union([z.string(), z.null()]).optional(),
@@ -746,6 +744,10 @@ export const CreateBotResponse = z.object({
credentialHeader: z.string(),
credentialScopeHeader: z.string(),
credentialScope: z.string(),
+ credentialLabel: z.union([z.string(), z.null()]).optional(),
+ credentialExpiresAt: z
+ .union([z.string().datetime({ offset: true }), z.null()])
+ .optional(),
}),
z.null(),
])
@@ -1516,8 +1518,6 @@ export const IssueBotCredential = z.object({
export const IssueBotCredentialResponse = z.object({
botId: z.string().uuid(),
- tokenId: z.string().uuid(),
- bearerToken: z.string(),
label: z.union([z.string(), z.null()]).optional(),
expiresAt: z
.union([z.string().datetime({ offset: true }), z.null()])
diff --git a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts
index 8eb179a3cf..2f99adef14 100644
--- a/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts
+++ b/apps/web/src/lib/service-clients/service-cognition/generated/tools/types.ts
@@ -1540,7 +1540,7 @@ export interface CrmCompanySearchDomain {
createdAt: string;
}
/**
- * Create a bot with a name, stable handle, and optional profile. Omit teamId for a bot owned by the current user; provide teamId to create a team-owned bot, which requires team administrator or owner permission. Pass channelId when the bot should post to a channel immediately: the current user must be a member of that channel. The response then includes a one-time bearerToken and that channel's webhook URL. Omit channelId to create the bot only, then use ManageBotChannelAccess and IssueBotCredential for later setup.
+ * Create a bot with a name, stable handle, and optional profile. Omit teamId for a bot owned by the current user; provide teamId to create a team-owned bot, which requires team administrator or owner permission. Pass channelId when the bot should post to a channel immediately: the current user must be a member of that channel. The response then includes that channel's webhook URL and a credential proposal. The user mints the bearer token from the chat card or bot settings; the secret is never returned in this tool result. Omit channelId to create the bot only, then use ManageBotChannelAccess and IssueBotCredential for later setup.
*/
export interface CreateBot {
/**
@@ -1564,15 +1564,15 @@ export interface CreateBot {
*/
avatarUrl?: string | null;
/**
- * Channel id to grant the new bot access to. Requires current-user channel membership. When set, the tool also mints a credential and returns the channel webhook URL.
+ * Channel id to grant the new bot access to. Requires current-user channel membership. When set, the tool also returns the channel webhook URL and a credential proposal the user can mint from the chat card.
*/
channelId?: string | null;
/**
- * Optional label for the credential minted when channelId is set, such as `github-webhook`. Requires channelId.
+ * Optional label for the credential the user will mint when channelId is set, such as `github-webhook`. Requires channelId.
*/
credentialLabel?: string | null;
/**
- * Optional RFC 3339 expiration for the credential minted when channelId is set. Requires channelId.
+ * Optional RFC 3339 expiration for the credential the user will mint when channelId is set. Requires channelId.
*/
credentialExpiresAt?: string | null;
/**
@@ -1586,7 +1586,7 @@ export interface CreateBot {
export interface CreateBotResponse {
bot: BotSummary;
/**
- * Credential and webhook returned when [`CreateBot::channel_id`] was set.
+ * Channel webhook and credential proposal returned when [`CreateBot::channel_id`] was set.
*/
channelSetup?: CreatedBotChannelSetup | null;
/**
@@ -1595,24 +1595,16 @@ export interface CreateBotResponse {
summary: string;
}
/**
- * One-time credential and webhook created with a channel-scoped bot.
+ * Channel webhook and credential proposal created with a channel-scoped bot.
*/
export interface CreatedBotChannelSetup {
/**
* Channel the bot can now post to.
*/
channelId: string;
- /**
- * Token metadata id, used to revoke this credential through the bot API.
- */
- tokenId: string;
- /**
- * Raw bearer token. It is returned only when minted and must be stored securely.
- */
- bearerToken: string;
webhook: BotWebhook;
/**
- * Header where callers send [`Self::bearer_token`].
+ * Header where callers send the minted bearer token.
*/
credentialHeader: string;
/**
@@ -1623,6 +1615,14 @@ export interface CreatedBotChannelSetup {
* Required scope value for the bot credential.
*/
credentialScope: string;
+ /**
+ * Optional label for the credential the user will mint from the chat card.
+ */
+ credentialLabel?: string | null;
+ /**
+ * Optional expiration for the credential the user will mint from the chat card.
+ */
+ credentialExpiresAt?: string | null;
}
/**
* One channel-specific webhook URL for a bot.
@@ -2293,7 +2293,7 @@ export interface EditTagResponse {
summary: string;
}
/**
- * Get the channel-specific webhook URLs for a bot the current user can manage. A bot has one URL per channel it can access. POST message content to a returned webhookUrl and authenticate with a token from IssueBotCredential or CreateBot in the returned credentialHeader; also send credentialScope in credentialScopeHeader. If no URLs are returned, add the bot to a channel with ManageBotChannelAccess or recreate it with CreateBot and channelId.
+ * Get the channel-specific webhook URLs for a bot the current user can manage. A bot has one URL per channel it can access. POST message content to a returned webhookUrl and authenticate with a token minted from the chat card or bot settings after IssueBotCredential or CreateBot; send it in the returned credentialHeader and send credentialScope in credentialScopeHeader. If no URLs are returned, add the bot to a channel with ManageBotChannelAccess or recreate it with CreateBot and channelId.
*/
export interface GetBotWebhooks {
/**
@@ -2310,7 +2310,7 @@ export interface GetBotWebhooksResponse {
*/
botId: string;
/**
- * Header where callers send a bearer token from [`super::IssueBotCredential`].
+ * Header where callers send a bearer token minted from the chat card or bot settings.
*/
credentialHeader: string;
/**
@@ -2683,7 +2683,7 @@ export interface ImportNotionPageResponse {
message: string;
}
/**
- * Mint a new secret bearer token for a bot the current user can manage. Use this when the user asks for bot credentials or a webhook token; existing raw secrets cannot be recovered safely. The response contains a newly issued bearerToken and tokenId. Treat bearerToken as sensitive and tell the user to store it securely because it is shown only once.
+ * Prepare a new bot credential for a bot the current user can manage. This does not mint the secret. Tell the user to click the chat card or open bot settings to create the token. The secret is shown only while that card is open. Use this when the user asks for bot credentials or a webhook token; existing raw secrets cannot be recovered safely.
*/
export interface IssueBotCredential {
/**
@@ -2700,21 +2700,13 @@ export interface IssueBotCredential {
expiresAt?: string | null;
}
/**
- * Response containing a newly issued bot credential.
+ * Response describing a credential the user can mint from the chat card.
*/
export interface IssueBotCredentialResponse {
/**
* Bot receiving the credential.
*/
botId: string;
- /**
- * Token metadata id, used to revoke this credential through the bot API.
- */
- tokenId: string;
- /**
- * Raw bearer token. It is returned only when minted and must be stored securely.
- */
- bearerToken: string;
/**
* Optional credential label.
*/
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/botToken.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/botToken.ts
index 789d8a1ffe..382ed8d31c 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/botToken.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/botToken.ts
@@ -28,6 +28,6 @@ export interface BotToken {
last_used_at?: BotTokenLastUsedAt;
/** Revocation timestamp. */
revoked_at?: BotTokenRevokedAt;
- /** Raw bearer token. */
- token: string;
+ /** Display prefix of the bearer token. The raw secret is never stored here. */
+ token_prefix: string;
}
diff --git a/apps/web/src/lib/service-clients/service-storage/openapi.json b/apps/web/src/lib/service-clients/service-storage/openapi.json
index 07eab5243f..98414b7d52 100644
--- a/apps/web/src/lib/service-clients/service-storage/openapi.json
+++ b/apps/web/src/lib/service-clients/service-storage/openapi.json
@@ -12762,7 +12762,7 @@
"BotToken": {
"type": "object",
"description": "Bot token metadata.",
- "required": ["id", "bot_id", "token", "created_at"],
+ "required": ["id", "bot_id", "token_prefix", "created_at"],
"properties": {
"bot_id": {
"$ref": "#/components/schemas/BotId",
@@ -12797,9 +12797,9 @@
"format": "date-time",
"description": "Revocation timestamp."
},
- "token": {
+ "token_prefix": {
"type": "string",
- "description": "Raw bearer token."
+ "description": "Display prefix of the bearer token. The raw secret is never stored here."
}
}
},
diff --git a/crates/bot_token/Cargo.toml b/crates/bot_token/Cargo.toml
new file mode 100644
index 0000000000..c3b397e46e
--- /dev/null
+++ b/crates/bot_token/Cargo.toml
@@ -0,0 +1,9 @@
+[package]
+edition = "2024"
+name = "bot_token"
+publish = false
+version = "0.1.0"
+
+[dependencies]
+sha2 = { workspace = true }
+workspace-hack = { version = "0.1", path = "../workspace-hack" }
diff --git a/crates/bot_token/src/lib.rs b/crates/bot_token/src/lib.rs
new file mode 100644
index 0000000000..9024612081
--- /dev/null
+++ b/crates/bot_token/src/lib.rs
@@ -0,0 +1,70 @@
+//! Hash and display-prefix helpers for bot bearer tokens.
+//!
+//! Mint (`bots`) and auth-time lookup (`macro_authorization`) both persist or
+//! match `token_hash`. This crate owns that digest so the two sides cannot
+//! drift, without either crate depending on the other.
+
+#![deny(missing_docs)]
+
+use sha2::{Digest, Sha256};
+
+#[cfg(test)]
+mod test;
+
+/// Number of characters used as a fallback display prefix.
+const FALLBACK_PREFIX_CHARS: usize = 12;
+
+/// SHA-256 of a raw bot bearer token's UTF-8 bytes.
+pub fn hash_token(token: &str) -> [u8; 32] {
+ Sha256::digest(token.as_bytes()).into()
+}
+
+/// Display prefix for a bot bearer token.
+///
+/// Current tokens look like `mbot_<hex>_<secret>`. The displayed prefix is
+/// `mbot_<hex>`. Tokens that do not match that shape use the first 12 hex
+/// characters of the SHA-256, never a raw substring of the secret.
+pub fn token_prefix(token: &str) -> String {
+ if let Some(rest) = token.strip_prefix("mbot_")
+ && let Some((prefix, _)) = rest.split_once('_')
+ && !prefix.is_empty()
+ {
+ return format!("mbot_{prefix}");
+ }
+ fallback_prefix(token)
+}
+
+fn fallback_prefix(token: &str) -> String {
+ hash_token(token)
+ .into_iter()
+ .take(FALLBACK_PREFIX_CHARS / 2)
+ .fold(
+ String::with_capacity(FALLBACK_PREFIX_CHARS),
+ |mut out, byte| {
+ use std::fmt::Write;
+ let _ = write!(out, "{byte:02x}");
+ out
+ },
+ )
+}
+
+/// Hash and display prefix derived from a raw bot bearer token.
+///
+/// Persist this. Never persist the raw secret.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct HashedBotToken {
+ /// SHA-256 of the raw token UTF-8 bytes.
+ pub hash: [u8; 32],
+ /// Display prefix (`mbot_<hex>` or a hash-derived fallback).
+ pub prefix: String,
+}
+
+impl HashedBotToken {
+ /// Hash a raw bearer token for storage.
+ pub fn from_raw(token: &str) -> Self {
+ Self {
+ hash: hash_token(token),
+ prefix: token_prefix(token),
+ }
+ }
+}
diff --git a/crates/bot_token/src/test.rs b/crates/bot_token/src/test.rs
new file mode 100644
index 0000000000..70c318aca8
--- /dev/null
+++ b/crates/bot_token/src/test.rs
@@ -0,0 +1,51 @@
+use super::*;
+
+#[test]
+fn hashes_utf8_bytes_with_sha256() {
+ use sha2::{Digest, Sha256};
+
+ let hash = hash_token("mbot_abc_secret");
+ let expected: [u8; 32] = Sha256::digest(b"mbot_abc_secret").into();
+ assert_eq!(hash, expected);
+ assert_ne!(hash, hash_token("mbot_abc_other"));
+}
+
+#[test]
+fn token_prefix_uses_mbot_segment_or_hash_fallback() {
+ assert_eq!(
+ token_prefix("mbot_aabbccddeeff_aabbccddeeffrest"),
+ "mbot_aabbccddeeff"
+ );
+
+ let leftover = "550e8400-e29b-41d4-a716-446655440000";
+ let leftover_prefix = token_prefix(leftover);
+ assert_eq!(leftover_prefix.len(), 12);
+ assert_ne!(leftover_prefix, leftover);
+ assert_eq!(
+ leftover_prefix,
+ hash_token(leftover)
+ .into_iter()
+ .take(6)
+ .fold(String::new(), |mut out, byte| {
+ use std::fmt::Write;
+ let _ = write!(out, "{byte:02x}");
+ out
+ })
+ );
+
+ assert_eq!(token_prefix("short").len(), 12);
+ assert_ne!(token_prefix("short"), "short");
+}
+
+#[test]
+fn hashed_bot_token_does_not_retain_the_raw_secret() {
+ let raw = "mbot_aabbccddeeff_aabbccddeeffsecret";
+ let hashed = HashedBotToken::from_raw(raw);
+ assert_eq!(hashed.hash, hash_token(raw));
+ assert_eq!(hashed.prefix, "mbot_aabbccddeeff");
+ assert_ne!(hashed.prefix, raw);
+
+ let short = HashedBotToken::from_raw("short");
+ assert_ne!(short.prefix, "short");
+ assert_eq!(short.hash, hash_token("short"));
+}
diff --git a/crates/bots/Cargo.toml b/crates/bots/Cargo.toml
index 8faeb66823..3f21ec8eef 100644
--- a/crates/bots/Cargo.toml
+++ b/crates/bots/Cargo.toml
@@ -37,6 +37,7 @@ anyhow = { workspace = true }
async-trait = { workspace = true, optional = true }
axum = { workspace = true, optional = true }
bot_id = { path = "../bot_id", features = ["schema"] }
+bot_token = { path = "../bot_token" }
channels = { path = "../channels", optional = true, default-features = false, features = ["ports"] }
chrono = { workspace = true }
entity_access = { path = "../entity_access", optional = true, default-features = false }
diff --git a/crates/bots/src/domain/models.rs b/crates/bots/src/domain/models.rs
index 277f0d0f72..39004dddfd 100644
--- a/crates/bots/src/domain/models.rs
+++ b/crates/bots/src/domain/models.rs
@@ -164,8 +164,8 @@ pub struct BotToken {
pub id: Uuid,
/// Owning bot id.
pub bot_id: BotId,
- /// Raw bearer token.
- pub token: String,
+ /// Display prefix of the bearer token. The raw secret is never stored here.
+ pub token_prefix: String,
/// Optional token label.
pub label: Option<String>,
/// Last successful use.
diff --git a/crates/bots/src/domain/ports.rs b/crates/bots/src/domain/ports.rs
index 4107c90e67..3fb58c64a5 100644
--- a/crates/bots/src/domain/ports.rs
+++ b/crates/bots/src/domain/ports.rs
@@ -5,6 +5,7 @@ use super::models::{
BotTokenCandidate, CreateBotRequest, CreateBotTokenRequest, CreateBotTokenResponse,
CreateChannelScopedBotRequest, CreateChannelScopedBotResponse, PatchBotRequest,
};
+use bot_token::HashedBotToken;
use entity_access::domain::models::{EntityAccessReceipt, MemberParticipantRole};
use macro_user_id::user_id::MacroUserIdStr;
use std::future::Future;
@@ -24,13 +25,13 @@ pub trait BotRepo: Send + Sync + 'static {
req: CreateBotRequest,
) -> impl Future<Output = Result<Bot, Self::Err>> + Send;
- /// Create an owned bot, add it to a channel, and create a token atomically.
+ /// Create an owned bot, add it to a channel, and persist a hashed token atomically.
fn create_channel_scoped_bot(
&self,
owner: BotOwner,
created_by: MacroUserIdStr<'static>,
channel_id: Uuid,
- token: String,
+ token: HashedBotToken,
req: CreateChannelScopedBotRequest,
) -> impl Future<Output = Result<(Bot, BotToken), Self::Err>> + Send;
@@ -101,11 +102,11 @@ pub trait BotRepo: Send + Sync + 'static {
channel_id: Uuid,
) -> impl Future<Output = Result<Vec<Bot>, Self::Err>> + Send;
- /// Create a token.
+ /// Persist a hashed token. The raw secret must not be passed here.
fn create_token(
&self,
bot_id: BotId,
- token: String,
+ token: HashedBotToken,
req: CreateBotTokenRequest,
) -> impl Future<Output = Result<BotToken, Self::Err>> + Send;
@@ -122,13 +123,13 @@ pub trait BotRepo: Send + Sync + 'static {
token_id: Uuid,
) -> impl Future<Output = Result<bool, Self::Err>> + Send;
- /// Lookup a token candidate by exact raw token value.
+ /// Lookup a token candidate by hashing the presented raw token.
fn token_candidate(
&self,
token: &str,
) -> impl Future<Output = Result<Option<BotTokenCandidate>, Self::Err>> + Send;
- /// Lookup a channel-scoped token candidate by exact raw token value.
+ /// Lookup a channel-scoped token candidate by hashing the presented raw token.
fn channel_token_candidate(
&self,
channel_id: Uuid,
diff --git a/crates/bots/src/domain/service.rs b/crates/bots/src/domain/service.rs
index c8778d9a81..877fe101a6 100644
--- a/crates/bots/src/domain/service.rs
+++ b/crates/bots/src/domain/service.rs
@@ -10,6 +10,7 @@ use super::{
ports::{BotError, BotRepo, BotService},
tokens,
};
+use bot_token::HashedBotToken;
use chrono::{DateTime, Utc};
use entity_access::domain::models::{EntityAccessReceipt, EntityType, MemberParticipantRole};
use macro_event_broker::MacroEventBroker;
@@ -199,10 +200,16 @@ where
let generated_token = tokens::generate_token();
let (bot, token) = self
.repo
- .create_channel_scoped_bot(owner, caller, channel_id, generated_token, req)
+ .create_channel_scoped_bot(
+ owner,
+ caller,
+ channel_id,
+ HashedBotToken::from_raw(&generated_token),
+ req,
+ )
.await
.map_err(|err| BotError::Repo(err.into()))?;
- let bot_token = token.token.clone();
+ let bot_token = generated_token;
self.publish_bot_event(&BotMacroEvent::created(BotCreatedMetadata {
bot_id: bot.id,
@@ -387,14 +394,13 @@ where
let generated_token = tokens::generate_token();
let token = self
.repo
- .create_token(bot_id, generated_token, req)
+ .create_token(bot_id, HashedBotToken::from_raw(&generated_token), req)
.await
.map_err(|err| BotError::Repo(err.into()))?;
- let bearer_token = token.token.clone();
Ok(super::models::CreateBotTokenResponse {
token,
- bearer_token,
+ bearer_token: generated_token,
})
}
diff --git a/crates/bots/src/inbound/channel_webhook_router/tests.rs b/crates/bots/src/inbound/channel_webhook_router/tests.rs
index c4de817657..ce4e533f44 100644
--- a/crates/bots/src/inbound/channel_webhook_router/tests.rs
+++ b/crates/bots/src/inbound/channel_webhook_router/tests.rs
@@ -695,7 +695,7 @@ fn scoped_bot_response(bot_id: BotId) -> CreateChannelScopedBotResponse {
token: BotToken {
id: Uuid::new_v4(),
bot_id,
- token: bot_token.clone(),
+ token_prefix: "mbot_test".to_string(),
label: Some("webhook".to_string()),
last_used_at: None,
expires_at: None,
diff --git a/crates/bots/src/inbound/toolset/create_bot.rs b/crates/bots/src/inbound/toolset/create_bot.rs
index f83df6b9de..55a5c790ae 100644
--- a/crates/bots/src/inbound/toolset/create_bot.rs
+++ b/crates/bots/src/inbound/toolset/create_bot.rs
@@ -4,10 +4,7 @@ use super::{
BOT_WEBHOOK_SCOPE, BOT_WEBHOOK_SCOPE_HEADER, BOT_WEBHOOK_TOKEN_HEADER, BotSummary,
BotToolContext, BotWebhook, CreatedBotChannelSetup, bot_tool_error,
};
-use crate::domain::{
- models::{CreateBotRequest, CreateChannelScopedBotRequest},
- ports::BotService,
-};
+use crate::domain::{models::CreateBotRequest, ports::BotService};
use ai_toolset::{
AsyncTool, RequestContext, ServiceContext, ToolAnnotated, ToolAnnotations, ToolCallError,
ToolResult,
@@ -25,7 +22,7 @@ use uuid::Uuid;
pub struct CreateBotResponse {
/// Newly created bot.
pub bot: BotSummary,
- /// Credential and webhook returned when [`CreateBot::channel_id`] was set.
+ /// Channel webhook and credential proposal returned when [`CreateBot::channel_id`] was set.
pub channel_setup: Option<CreatedBotChannelSetup>,
/// Human-readable result summary.
pub summary: String,
@@ -36,7 +33,7 @@ pub struct CreateBotResponse {
#[serde(rename_all = "camelCase")]
#[schemars(
title = "CreateBot",
- description = "Create a bot with a name, stable handle, and optional profile. Omit teamId for a bot owned by the current user; provide teamId to create a team-owned bot, which requires team administrator or owner permission. Pass channelId when the bot should post to a channel immediately: the current user must be a member of that channel. The response then includes a one-time bearerToken and that channel's webhook URL. Omit channelId to create the bot only, then use ManageBotChannelAccess and IssueBotCredential for later setup."
+ description = "Create a bot with a name, stable handle, and optional profile. Omit teamId for a bot owned by the current user; provide teamId to create a team-owned bot, which requires team administrator or owner permission. Pass channelId when the bot should post to a channel immediately: the current user must be a member of that channel. The response then includes that channel's webhook URL and a credential proposal. The user mints the bearer token from the chat card or bot settings; the secret is never returned in this tool result. Omit channelId to create the bot only, then use ManageBotChannelAccess and IssueBotCredential for later setup."
)]
pub struct CreateBot {
/// Team owner; omit for a user-owned bot.
@@ -65,19 +62,19 @@ pub struct CreateBot {
pub avatar_url: Option<String>,
/// Optional channel to grant immediately.
#[schemars(
- description = "Channel id to grant the new bot access to. Requires current-user channel membership. When set, the tool also mints a credential and returns the channel webhook URL."
+ description = "Channel id to grant the new bot access to. Requires current-user channel membership. When set, the tool also returns the channel webhook URL and a credential proposal the user can mint from the chat card."
)]
#[serde(default)]
pub channel_id: Option<Uuid>,
/// Optional credential label used only with [`Self::channel_id`].
#[schemars(
- description = "Optional label for the credential minted when channelId is set, such as `github-webhook`. Requires channelId."
+ description = "Optional label for the credential the user will mint when channelId is set, such as `github-webhook`. Requires channelId."
)]
#[serde(default)]
pub credential_label: Option<String>,
/// Optional credential expiry used only with [`Self::channel_id`].
#[schemars(
- description = "Optional RFC 3339 expiration for the credential minted when channelId is set. Requires channelId."
+ description = "Optional RFC 3339 expiration for the credential the user will mint when channelId is set. Requires channelId."
)]
#[serde(default)]
pub credential_expires_at: Option<DateTime<Utc>>,
@@ -174,32 +171,47 @@ impl CreateBot {
Svc: BotService,
AccessSvc: EntityAccessService,
{
- service_context
+ let access = service_context
.require_channel_member(&request_context, channel_id)
.await?;
- let created = service_context
+ let caller = request_context.user_id.clone();
+ let bot = service_context
.service
- .create_channel_scoped_bot(
- request_context.user_id,
- channel_id,
- CreateChannelScopedBotRequest {
+ .create_bot(
+ caller.clone(),
+ CreateBotRequest {
team_id: self.team_id,
name: self.name.clone(),
handle: self.handle.clone(),
description: self.description.clone(),
avatar_url: self.avatar_url.clone(),
- token_label: self.credential_label.clone(),
- token_expires_at: self.credential_expires_at,
has_agent: self.has_agent,
},
)
.await
.map_err(|error| bot_tool_error("create bot", error))?;
- let bot = BotSummary::try_from(created.bot)?;
+ if let Err(error) = service_context
+ .service
+ .add_bot_to_channel(access, bot.id)
+ .await
+ {
+ let _ = service_context
+ .service
+ .delete_bot(caller, bot.id)
+ .await
+ .inspect_err(|cleanup_error| {
+ tracing::error!(
+ error=?cleanup_error,
+ "failed to delete bot after channel grant failed"
+ );
+ });
+ return Err(bot_tool_error("grant bot channel access", error));
+ }
+ let bot = BotSummary::try_from(bot)?;
let webhook =
BotWebhook::for_channel(&service_context.document_storage_service_url, channel_id);
let summary = format!(
- "Created bot @{} and granted it access to the channel. Store the bearer token securely; it will not be shown again.",
+ "Created bot @{} and granted it access to the channel. Click the card or open bot settings to create a token. The secret is shown only while that card is open.",
bot.handle
);
@@ -207,12 +219,12 @@ impl CreateBot {
bot,
channel_setup: Some(CreatedBotChannelSetup {
channel_id,
- token_id: created.token.id,
- bearer_token: created.bot_token,
webhook,
credential_header: BOT_WEBHOOK_TOKEN_HEADER.to_string(),
credential_scope_header: BOT_WEBHOOK_SCOPE_HEADER.to_string(),
credential_scope: BOT_WEBHOOK_SCOPE.to_string(),
+ credential_label: self.credential_label.clone(),
+ credential_expires_at: self.credential_expires_at,
}),
summary,
})
diff --git a/crates/bots/src/inbound/toolset/get_bot_webhooks.rs b/crates/bots/src/inbound/toolset/get_bot_webhooks.rs
index d8e7fdc2a3..d84ca120a3 100644
--- a/crates/bots/src/inbound/toolset/get_bot_webhooks.rs
+++ b/crates/bots/src/inbound/toolset/get_bot_webhooks.rs
@@ -23,7 +23,7 @@ use uuid::Uuid;
pub struct GetBotWebhooksResponse {
/// Bot whose webhook URLs were requested.
pub bot_id: Uuid,
- /// Header where callers send a bearer token from [`super::IssueBotCredential`].
+ /// Header where callers send a bearer token minted from the chat card or bot settings.
pub credential_header: String,
/// Header where callers send [`Self::credential_scope`].
pub credential_scope_header: String,
@@ -40,7 +40,7 @@ pub struct GetBotWebhooksResponse {
#[serde(rename_all = "camelCase")]
#[schemars(
title = "GetBotWebhooks",
- description = "Get the channel-specific webhook URLs for a bot the current user can manage. A bot has one URL per channel it can access. POST message content to a returned webhookUrl and authenticate with a token from IssueBotCredential or CreateBot in the returned credentialHeader; also send credentialScope in credentialScopeHeader. If no URLs are returned, add the bot to a channel with ManageBotChannelAccess or recreate it with CreateBot and channelId."
+ description = "Get the channel-specific webhook URLs for a bot the current user can manage. A bot has one URL per channel it can access. POST message content to a returned webhookUrl and authenticate with a token minted from the chat card or bot settings after IssueBotCredential or CreateBot; send it in the returned credentialHeader and send credentialScope in credentialScopeHeader. If no URLs are returned, add the bot to a channel with ManageBotChannelAccess or recreate it with CreateBot and channelId."
)]
pub struct GetBotWebhooks {
/// Bot to inspect.
diff --git a/crates/bots/src/inbound/toolset/issue_bot_credential.rs b/crates/bots/src/inbound/toolset/issue_bot_credential.rs
index 300c1549df..afcf455fcd 100644
--- a/crates/bots/src/inbound/toolset/issue_bot_credential.rs
+++ b/crates/bots/src/inbound/toolset/issue_bot_credential.rs
@@ -1,10 +1,7 @@
//! IssueBotCredential tool.
use super::{BotToolContext, bot_tool_error};
-use crate::domain::{
- models::{BotId, CreateBotTokenRequest},
- ports::BotService,
-};
+use crate::domain::{models::BotId, ports::BotService};
use ai_toolset::{
AsyncTool, RequestContext, ServiceContext, ToolAnnotated, ToolAnnotations, ToolResult,
};
@@ -15,16 +12,12 @@ use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use uuid::Uuid;
-/// Response containing a newly issued bot credential.
+/// Response describing a credential the user can mint from the chat card.
#[derive(Debug, Serialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct IssueBotCredentialResponse {
/// Bot receiving the credential.
pub bot_id: Uuid,
- /// Token metadata id, used to revoke this credential through the bot API.
- pub token_id: Uuid,
- /// Raw bearer token. It is returned only when minted and must be stored securely.
- pub bearer_token: String,
/// Optional credential label.
pub label: Option<String>,
/// Optional expiration time.
@@ -33,12 +26,12 @@ pub struct IssueBotCredentialResponse {
pub summary: String,
}
-/// Mint a new secret credential for a manageable bot.
+/// Propose a new secret credential for a manageable bot without minting it.
#[derive(Debug, Clone, Deserialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
#[schemars(
title = "IssueBotCredential",
- description = "Mint a new secret bearer token for a bot the current user can manage. Use this when the user asks for bot credentials or a webhook token; existing raw secrets cannot be recovered safely. The response contains a newly issued bearerToken and tokenId. Treat bearerToken as sensitive and tell the user to store it securely because it is shown only once."
+ description = "Prepare a new bot credential for a bot the current user can manage. This does not mint the secret. Tell the user to click the chat card or open bot settings to create the token. The secret is shown only while that card is open. Use this when the user asks for bot credentials or a webhook token; existing raw secrets cannot be recovered safely."
)]
pub struct IssueBotCredential {
/// Bot to issue a credential for.
@@ -80,27 +73,17 @@ where
service_context: ServiceContext<BotToolContext<Svc, AccessSvc>>,
request_context: RequestContext,
) -> ToolResult<Self::Output> {
- let response = service_context
+ service_context
.service
- .create_token(
- request_context.user_id,
- BotId::new_from_uuid(self.bot_id),
- CreateBotTokenRequest {
- label: self.label.clone(),
- expires_at: self.expires_at,
- },
- )
+ .get_bot(request_context.user_id, BotId::new_from_uuid(self.bot_id))
.await
.map_err(|error| bot_tool_error("issue bot credential", error))?;
Ok(IssueBotCredentialResponse {
bot_id: self.bot_id,
- token_id: response.token.id,
- bearer_token: response.bearer_token,
- label: response.token.label,
- expires_at: response.token.expires_at,
- summary: "Issued a new bot credential. Store the bearer token securely; it will not be shown again."
- .to_string(),
+ label: self.label.clone(),
+ expires_at: self.expires_at,
+ summary: "Credential is ready to mint. Click the card or open bot settings to create a token. The secret is shown only while that card is open.".to_string(),
})
}
}
diff --git a/crates/bots/src/inbound/toolset/test.rs b/crates/bots/src/inbound/toolset/test.rs
index 862cbe085e..fe21ea77f4 100644
--- a/crates/bots/src/inbound/toolset/test.rs
+++ b/crates/bots/src/inbound/toolset/test.rs
@@ -2,6 +2,7 @@ use super::{
BotOwnerSummary, BotSummary, BotToolContext, bot_tool_error,
create_bot::CreateBot,
get_bot_webhooks::GetBotWebhooks,
+ issue_bot_credential::IssueBotCredential,
manage_bot_channel_access::{BotChannelAccessAction, ManageBotChannelAccess},
};
use crate::domain::models::{
@@ -61,7 +62,7 @@ fn sample_token(bot_id: BotId, label: Option<String>) -> BotToken {
BotToken {
id: Uuid::new_v4(),
bot_id,
- token: "secret-token".to_string(),
+ token_prefix: "mbot_secret".to_string(),
label,
last_used_at: None,
expires_at: None,
@@ -76,6 +77,9 @@ struct ToolTestBotService {
remove_calls: Arc<AtomicUsize>,
created: Arc<Mutex<Option<CreateBotRequest>>>,
scoped: Arc<Mutex<Option<(Uuid, CreateChannelScopedBotRequest)>>>,
+ added: Arc<Mutex<Option<BotId>>>,
+ deleted: Arc<Mutex<Option<BotId>>>,
+ add_error: Option<String>,
}
impl BotService for ToolTestBotService {
@@ -111,9 +115,11 @@ impl BotService for ToolTestBotService {
async fn get_bot(
&self,
_caller: MacroUserIdStr<'static>,
- _bot_id: BotId,
+ bot_id: BotId,
) -> Result<Bot, BotError> {
- unimplemented!()
+ let mut bot = sample_bot("build-bot");
+ bot.id = bot_id;
+ Ok(bot)
}
async fn get_self(&self, _bot_id: BotId) -> Result<Bot, BotError> {
@@ -132,17 +138,22 @@ impl BotService for ToolTestBotService {
async fn delete_bot(
&self,
_caller: MacroUserIdStr<'static>,
- _bot_id: BotId,
+ bot_id: BotId,
) -> Result<(), BotError> {
- unimplemented!()
+ *self.deleted.lock().expect("delete lock") = Some(bot_id);
+ Ok(())
}
async fn add_bot_to_channel(
&self,
_access: EntityAccessReceipt<MemberParticipantRole>,
- _bot_id: BotId,
+ bot_id: BotId,
) -> Result<(), BotError> {
- unimplemented!()
+ if let Some(message) = &self.add_error {
+ return Err(BotError::Repo(anyhow::anyhow!(message.clone())));
+ }
+ *self.added.lock().expect("add lock") = Some(bot_id);
+ Ok(())
}
async fn remove_bot_from_channel(
@@ -454,10 +465,12 @@ async fn create_bot_rejects_credential_fields_without_channel() {
}
#[tokio::test]
-async fn create_bot_for_channel_returns_credential_and_webhook() {
+async fn create_bot_for_channel_returns_webhook_and_credential_proposal() {
let channel_id = Uuid::new_v4();
let service = ToolTestBotService::default();
+ let created = service.created.clone();
let scoped = service.scoped.clone();
+ let added = service.added.clone();
let access = AllowingEntityAccessService::default();
let access_calls = access.calls.clone();
let context = BotToolContext::new(service, access, "https://storage.example.com/".to_string());
@@ -479,16 +492,40 @@ async fn create_bot_for_channel_returns_credential_and_webhook() {
let setup = response.channel_setup.expect("channel setup");
assert_eq!(setup.channel_id, channel_id);
- assert_eq!(setup.bearer_token, "secret-token");
+ assert_eq!(setup.credential_label.as_deref(), Some("github-webhook"));
assert_eq!(
setup.webhook.webhook_url,
format!("https://storage.example.com/channels/{channel_id}/webhook")
);
assert_eq!(setup.credential_header, "x-macro-bot-token");
assert_eq!(access_calls.load(Ordering::SeqCst), 1);
- let (scoped_channel, scoped_req) = scoped.lock().expect("scoped lock").clone().expect("scoped");
- assert_eq!(scoped_channel, channel_id);
- assert_eq!(scoped_req.token_label.as_deref(), Some("github-webhook"));
+ assert!(created.lock().expect("create lock").is_some());
+ assert!(added.lock().expect("add lock").is_some());
+ assert!(scoped.lock().expect("scoped lock").is_none());
+}
+
+#[tokio::test]
+async fn issue_bot_credential_returns_proposal_without_minting() {
+ let bot_id = Uuid::new_v4();
+ let service = ToolTestBotService::default();
+ let context = BotToolContext::new(
+ service,
+ NoOpEntityAccessService,
+ "https://storage.example.com".to_string(),
+ );
+
+ let response = IssueBotCredential {
+ bot_id,
+ label: Some("github-webhook".to_string()),
+ expires_at: None,
+ }
+ .call(ServiceContext(context), RequestContext::new(user_id()))
+ .await
+ .expect("manageable bot can receive a credential proposal");
+
+ assert_eq!(response.bot_id, bot_id);
+ assert_eq!(response.label.as_deref(), Some("github-webhook"));
+ assert!(response.summary.contains("ready to mint"));
}
#[tokio::test]
@@ -517,6 +554,40 @@ async fn create_bot_for_channel_requires_membership() {
assert_eq!(error.description, "failed to verify channel membership");
}
+#[tokio::test]
+async fn create_bot_for_channel_deletes_bot_when_grant_fails() {
+ let service = ToolTestBotService {
+ add_error: Some("channel grant failed".to_string()),
+ ..ToolTestBotService::default()
+ };
+ let deleted = service.deleted.clone();
+ let created = service.created.clone();
+ let context = BotToolContext::new(
+ service,
+ AllowingEntityAccessService::default(),
+ "https://storage.example.com".to_string(),
+ );
+
+ let error = CreateBot {
+ team_id: None,
+ name: "Build Bot".to_string(),
+ handle: "build-bot".to_string(),
+ description: None,
+ avatar_url: None,
+ channel_id: Some(Uuid::new_v4()),
+ credential_label: None,
+ credential_expires_at: None,
+ has_agent: None,
+ }
+ .call(ServiceContext(context), RequestContext::new(user_id()))
+ .await
+ .expect_err("failed channel grant should not leave a channel-ready bot");
+
+ assert_eq!(error.description, "failed to grant bot channel access");
+ assert!(created.lock().expect("create lock").is_some());
+ assert!(deleted.lock().expect("delete lock").is_some());
+}
+
#[tokio::test]
async fn revoke_does_not_require_current_channel_membership() {
let service = ToolTestBotService::default();
diff --git a/crates/bots/src/inbound/toolset/types.rs b/crates/bots/src/inbound/toolset/types.rs
index 06d9e665a2..818044306e 100644
--- a/crates/bots/src/inbound/toolset/types.rs
+++ b/crates/bots/src/inbound/toolset/types.rs
@@ -2,6 +2,7 @@
use crate::domain::models::{Bot, BotOwner};
use ai_toolset::ToolCallError;
+use chrono::{DateTime, Utc};
use schemars::JsonSchema;
use serde::Serialize;
use uuid::Uuid;
@@ -104,22 +105,22 @@ impl BotWebhook {
}
}
-/// One-time credential and webhook created with a channel-scoped bot.
+/// Channel webhook and credential proposal created with a channel-scoped bot.
#[derive(Debug, Clone, Serialize, JsonSchema)]
#[serde(rename_all = "camelCase")]
pub struct CreatedBotChannelSetup {
/// Channel the bot can now post to.
pub channel_id: Uuid,
- /// Token metadata id, used to revoke this credential through the bot API.
- pub token_id: Uuid,
- /// Raw bearer token. It is returned only when minted and must be stored securely.
- pub bearer_token: String,
/// Channel webhook the credential authenticates against.
pub webhook: BotWebhook,
- /// Header where callers send [`Self::bearer_token`].
+ /// Header where callers send the minted bearer token.
pub credential_header: String,
/// Header where callers send [`Self::credential_scope`].
pub credential_scope_header: String,
/// Required scope value for the bot credential.
pub credential_scope: String,
+ /// Optional label for the credential the user will mint from the chat card.
+ pub credential_label: Option<String>,
+ /// Optional expiration for the credential the user will mint from the chat card.
+ pub credential_expires_at: Option<DateTime<Utc>>,
}
diff --git a/crates/bots/src/outbound/pg_bots_repo.rs b/crates/bots/src/outbound/pg_bots_repo.rs
index c349ee6dd5..e148db436a 100644
--- a/crates/bots/src/outbound/pg_bots_repo.rs
+++ b/crates/bots/src/outbound/pg_bots_repo.rs
@@ -12,6 +12,7 @@ use crate::domain::{
ports::BotRepo,
};
use anyhow::Context;
+use bot_token::{HashedBotToken, hash_token};
use chrono::{DateTime, Utc};
use macro_user_id::user_id::MacroUserIdStr;
use sqlx::PgPool;
@@ -119,7 +120,7 @@ impl TryFrom<BotChannelRow> for BotChannel {
struct BotTokenRow {
id: Uuid,
bot_id: Uuid,
- token: String,
+ token_prefix: String,
label: Option<String>,
last_used_at: Option<DateTime<Utc>>,
expires_at: Option<DateTime<Utc>>,
@@ -132,7 +133,7 @@ impl From<BotTokenRow> for BotToken {
Self {
id: row.id,
bot_id: BotId::new_from_uuid(row.bot_id),
- token: row.token,
+ token_prefix: row.token_prefix,
label: row.label,
last_used_at: row.last_used_at,
expires_at: row.expires_at,
@@ -146,7 +147,7 @@ impl From<BotTokenRow> for BotToken {
struct TokenCandidateRow {
token_id: Uuid,
bot_id: Uuid,
- token: String,
+ token_prefix: String,
label: Option<String>,
last_used_at: Option<DateTime<Utc>>,
expires_at: Option<DateTime<Utc>>,
@@ -165,7 +166,7 @@ impl TokenCandidateRow {
let token = BotToken {
id: self.token_id,
bot_id,
- token: self.token,
+ token_prefix: self.token_prefix,
label: self.label,
last_used_at: self.last_used_at,
expires_at: self.expires_at,
@@ -248,7 +249,7 @@ impl BotRepo for PgBotsRepo {
owner: BotOwner,
created_by: MacroUserIdStr<'static>,
channel_id: Uuid,
- token: String,
+ token: HashedBotToken,
req: CreateChannelScopedBotRequest,
) -> Result<(Bot, BotToken), Self::Err> {
let bot_id = BotId::new_from_uuid(macro_uuid::generate_uuid_v7());
@@ -313,14 +314,15 @@ impl BotRepo for PgBotsRepo {
BotTokenRow,
r#"
INSERT INTO bot_tokens (
- id, bot_id, token, label, expires_at
+ id, bot_id, token_hash, token_prefix, label, expires_at
)
- VALUES ($1, $2, $3, $4, $5)
- RETURNING id, bot_id, token, label, last_used_at, expires_at, revoked_at, created_at
+ VALUES ($1, $2, $3, $4, $5, $6)
+ RETURNING id, bot_id, token_prefix, label, last_used_at, expires_at, revoked_at, created_at
"#,
token_id,
bot_id.as_uuid(),
- token,
+ &token.hash[..],
+ token.prefix,
req.token_label,
req.token_expires_at,
)
@@ -658,7 +660,7 @@ impl BotRepo for PgBotsRepo {
async fn create_token(
&self,
bot_id: BotId,
- token: String,
+ token: HashedBotToken,
req: CreateBotTokenRequest,
) -> Result<BotToken, Self::Err> {
let token_id = macro_uuid::generate_uuid_v7();
@@ -666,14 +668,15 @@ impl BotRepo for PgBotsRepo {
BotTokenRow,
r#"
INSERT INTO bot_tokens (
- id, bot_id, token, label, expires_at
+ id, bot_id, token_hash, token_prefix, label, expires_at
)
- VALUES ($1, $2, $3, $4, $5)
- RETURNING id, bot_id, token, label, last_used_at, expires_at, revoked_at, created_at
+ VALUES ($1, $2, $3, $4, $5, $6)
+ RETURNING id, bot_id, token_prefix, label, last_used_at, expires_at, revoked_at, created_at
"#,
token_id,
bot_id.as_uuid(),
- token,
+ &token.hash[..],
+ token.prefix,
req.label,
req.expires_at,
)
@@ -687,7 +690,7 @@ impl BotRepo for PgBotsRepo {
let rows = sqlx::query_as!(
BotTokenRow,
r#"
- SELECT id, bot_id, token, label, last_used_at, expires_at, revoked_at, created_at
+ SELECT id, bot_id, token_prefix, label, last_used_at, expires_at, revoked_at, created_at
FROM bot_tokens
WHERE bot_id = $1
AND revoked_at IS NULL
@@ -720,13 +723,14 @@ impl BotRepo for PgBotsRepo {
}
async fn token_candidate(&self, token: &str) -> Result<Option<BotTokenCandidate>, Self::Err> {
+ let token_hash = hash_token(token);
let row = sqlx::query_as!(
TokenCandidateRow,
r#"
SELECT
bt.id AS token_id,
bt.bot_id,
- bt.token,
+ bt.token_prefix,
bt.label,
bt.last_used_at,
bt.expires_at,
@@ -735,10 +739,10 @@ impl BotRepo for PgBotsRepo {
b.kind
FROM bot_tokens bt
JOIN bots b ON b.id = bt.bot_id
- WHERE bt.token = $1
+ WHERE bt.token_hash = $1
AND b.deleted_at IS NULL
"#,
- token,
+ &token_hash[..],
)
.fetch_optional(&self.pool)
.await
@@ -752,13 +756,14 @@ impl BotRepo for PgBotsRepo {
channel_id: Uuid,
token: &str,
) -> Result<Option<BotTokenCandidate>, Self::Err> {
+ let token_hash = hash_token(token);
let row = sqlx::query_as!(
TokenCandidateRow,
r#"
SELECT
bt.id AS token_id,
bt.bot_id,
- bt.token,
+ bt.token_prefix,
bt.label,
bt.last_used_at,
bt.expires_at,
@@ -771,11 +776,11 @@ impl BotRepo for PgBotsRepo {
ON cp.channel_id = $1
AND cp.user_id = ('bot|' || b.id::text)
AND cp.left_at IS NULL
- WHERE bt.token = $2
+ WHERE bt.token_hash = $2
AND b.deleted_at IS NULL
"#,
channel_id,
- token,
+ &token_hash[..],
)
.fetch_optional(&self.pool)
.await
diff --git a/crates/bots/src/outbound/pg_bots_repo/tests.rs b/crates/bots/src/outbound/pg_bots_repo/tests.rs
index 3b6a439590..2f5387edea 100644
--- a/crates/bots/src/outbound/pg_bots_repo/tests.rs
+++ b/crates/bots/src/outbound/pg_bots_repo/tests.rs
@@ -644,7 +644,11 @@ async fn create_channel_scoped_bot_creates_bot_participant_and_token(
assert_eq!(created.bot.created_by.as_deref(), Some(USER_OWNER));
assert_eq!(created.token.bot_id, created.bot.id);
assert_eq!(created.token.label.as_deref(), Some("Webhook"));
- assert_eq!(created.token.token, created.bot_token);
+ assert_eq!(
+ created.token.token_prefix,
+ bot_token::token_prefix(&created.bot_token)
+ );
+ assert_ne!(created.token.token_prefix, created.bot_token);
assert_eq!(
active_channel_participant_count(&pool, channel_id, created.bot.id).await?,
1
@@ -767,7 +771,11 @@ async fn revoke_token_prevents_future_authentication(pool: PgPool) -> anyhow::Re
)
.await?;
- assert_eq!(created.token.token, created.bearer_token);
+ assert_eq!(
+ created.token.token_prefix,
+ bot_token::token_prefix(&created.bearer_token)
+ );
+ assert_ne!(created.token.token_prefix, created.bearer_token);
let authenticated = service.authenticate_token(&created.bearer_token).await?;
assert_eq!(authenticated.bot_id, bot.id);
@@ -787,7 +795,7 @@ async fn revoke_token_prevents_future_authentication(pool: PgPool) -> anyhow::Re
}
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
-async fn list_tokens_returns_raw_token_for_manageable_bot(pool: PgPool) -> anyhow::Result<()> {
+async fn list_tokens_returns_prefix_not_raw_secret(pool: PgPool) -> anyhow::Result<()> {
let service = service(&pool);
let bot = service
.create_bot(user_id(USER_OWNER), create_req("listed-token"))
@@ -809,7 +817,8 @@ async fn list_tokens_returns_raw_token_for_manageable_bot(pool: PgPool) -> anyho
assert_eq!(tokens.len(), 1);
assert_eq!(tokens[0].id, created.token.id);
assert_eq!(tokens[0].bot_id, bot.id);
- assert_eq!(tokens[0].token, created.bearer_token);
+ assert_eq!(tokens[0].token_prefix, created.token.token_prefix);
+ assert_ne!(tokens[0].token_prefix, created.bearer_token);
assert_eq!(tokens[0].label.as_deref(), Some("Listable"));
Ok(())
@@ -832,15 +841,17 @@ async fn authenticate_channel_token_accepts_migrated_uuid_token(
let token_id = Uuid::new_v4();
let raw_token = Uuid::new_v4().to_string();
+ let hashed = bot_token::HashedBotToken::from_raw(&raw_token);
sqlx::query(
r#"
- INSERT INTO bot_tokens (id, bot_id, token, label)
- VALUES ($1, $2, $3, $4)
+ INSERT INTO bot_tokens (id, bot_id, token_hash, token_prefix, label)
+ VALUES ($1, $2, $3, $4, $5)
"#,
)
.bind(token_id)
.bind(bot.id.as_uuid())
- .bind(&raw_token)
+ .bind(&hashed.hash[..])
+ .bind(&hashed.prefix)
.bind("migrated row")
.execute(&pool)
.await?;
@@ -856,6 +867,20 @@ async fn authenticate_channel_token_accepts_migrated_uuid_token(
Ok(())
}
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn rust_token_hash_matches_postgres_digest(pool: PgPool) -> anyhow::Result<()> {
+ let raw = "mbot_aabbccddeeff_aabbccddeeffsecret";
+ let rust_hash = bot_token::hash_token(raw);
+ let postgres_hash =
+ sqlx::query_scalar!(r#"SELECT digest(convert_to($1, 'UTF8'), 'sha256')"#, raw,)
+ .fetch_one(&pool)
+ .await?
+ .expect("pgcrypto digest returns bytea");
+
+ assert_eq!(rust_hash.as_slice(), postgres_hash.as_slice());
+ Ok(())
+}
+
#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
async fn lifecycle_creation_publishes_exact_sanitized_events(pool: PgPool) -> anyhow::Result<()> {
let broker = RecordingEventBroker::default();
diff --git a/crates/integration_tests/local_e2e/Cargo.toml b/crates/integration_tests/local_e2e/Cargo.toml
index 416dae26c5..7f63ec9d28 100644
--- a/crates/integration_tests/local_e2e/Cargo.toml
+++ b/crates/integration_tests/local_e2e/Cargo.toml
@@ -6,6 +6,7 @@ version = "0.1.0"
[dev-dependencies]
anyhow = { workspace = true }
+bot_token = { path = "../../bot_token" }
futures = { workspace = true }
local_e2e_test_support = { path = "../../local_e2e_test_support" }
reqwest = { workspace = true }
diff --git a/crates/integration_tests/local_e2e/tests/bot_entity_access.rs b/crates/integration_tests/local_e2e/tests/bot_entity_access.rs
index 73cfbe561e..f9622161e8 100644
--- a/crates/integration_tests/local_e2e/tests/bot_entity_access.rs
+++ b/crates/integration_tests/local_e2e/tests/bot_entity_access.rs
@@ -130,15 +130,17 @@ impl ScopedBotFixture {
.await
.context("failed to insert scoped bot")?;
+ let hashed = bot_token::HashedBotToken::from_raw(&bot_token);
sqlx::query(
r#"
- INSERT INTO bot_tokens (id, bot_id, token, label)
- VALUES ($1, $2, $3, 'local E2E scoped access')
+ INSERT INTO bot_tokens (id, bot_id, token_hash, token_prefix, label)
+ VALUES ($1, $2, $3, $4, 'local E2E scoped access')
"#,
)
.bind(bot_token_id)
.bind(bot_id)
- .bind(&bot_token)
+ .bind(&hashed.hash[..])
+ .bind(&hashed.prefix)
.execute(&mut *transaction)
.await
.context("failed to insert scoped bot token")?;
diff --git a/crates/macro_authorization/Cargo.toml b/crates/macro_authorization/Cargo.toml
index 7063691b97..b2c5c426ed 100644
--- a/crates/macro_authorization/Cargo.toml
+++ b/crates/macro_authorization/Cargo.toml
@@ -19,6 +19,7 @@ postgres = ["dep:sqlx"]
[dependencies]
axum = { workspace = true, optional = true }
bot_id = { path = "../bot_id" }
+bot_token = { path = "../bot_token" }
constant_time_eq = { workspace = true }
macro_auth = { path = "../macro_auth", optional = true }
macro_env_var = { path = "../macro_env_var", optional = true }
diff --git a/crates/macro_authorization/src/outbound/pg_bot_authorization.rs b/crates/macro_authorization/src/outbound/pg_bot_authorization.rs
index 6b621ce4e3..6d2a6096f0 100644
--- a/crates/macro_authorization/src/outbound/pg_bot_authorization.rs
+++ b/crates/macro_authorization/src/outbound/pg_bot_authorization.rs
@@ -101,6 +101,7 @@ impl BotAuthorizationRepo for PgBotAuthorizationRepo {
&self,
token: &str,
) -> Result<Option<BotTokenAuthorization>, Self::Err> {
+ let token_hash = bot_token::hash_token(token);
let row = sqlx::query_as!(
BotTokenAuthorizationRow,
r#"
@@ -112,12 +113,12 @@ impl BotAuthorizationRepo for PgBotAuthorizationRepo {
b.team_id
FROM bot_tokens bt
JOIN bots b ON b.id = bt.bot_id
- WHERE bt.token = $1
+ WHERE bt.token_hash = $1
AND bt.revoked_at IS NULL
AND (bt.expires_at IS NULL OR bt.expires_at > now())
AND b.deleted_at IS NULL
"#,
- token,
+ &token_hash[..],
)
.fetch_optional(&self.pool)
.await?;
diff --git a/crates/macro_authorization/src/outbound/pg_bot_authorization/test.rs b/crates/macro_authorization/src/outbound/pg_bot_authorization/test.rs
index 1c5daba0f8..955da497a0 100644
--- a/crates/macro_authorization/src/outbound/pg_bot_authorization/test.rs
+++ b/crates/macro_authorization/src/outbound/pg_bot_authorization/test.rs
@@ -28,14 +28,16 @@ async fn insert_bot_token(
.execute(pool)
.await
.unwrap();
+ let hashed = bot_token::HashedBotToken::from_raw(TOKEN);
sqlx::query!(
r#"
- INSERT INTO bot_tokens (id, bot_id, token, revoked_at)
- VALUES ($1, $2, $3, CASE WHEN $4 THEN now() ELSE NULL END)
+ INSERT INTO bot_tokens (id, bot_id, token_hash, token_prefix, revoked_at)
+ VALUES ($1, $2, $3, $4, CASE WHEN $5 THEN now() ELSE NULL END)
"#,
token_id,
bot_id,
- TOKEN,
+ &hashed.hash[..],
+ hashed.prefix,
revoked,
)
.execute(pool)
diff --git a/crates/macro_db_client/migrations/20260822144719_hash_bot_tokens.sql b/crates/macro_db_client/migrations/20260822144719_hash_bot_tokens.sql
new file mode 100644
index 0000000000..aae21001a2
--- /dev/null
+++ b/crates/macro_db_client/migrations/20260822144719_hash_bot_tokens.sql
@@ -0,0 +1,27 @@
+ALTER TABLE public.bot_tokens
+ ADD COLUMN token_hash bytea,
+ ADD COLUMN token_prefix text;
+
+UPDATE public.bot_tokens
+SET
+ token_hash = digest(convert_to(token, 'UTF8'), 'sha256'),
+ token_prefix = CASE
+ WHEN token LIKE 'mbot\_%' ESCAPE '\'
+ AND split_part(token, '_', 2) <> ''
+ THEN 'mbot_' || split_part(token, '_', 2)
+ ELSE left(token, 12)
+ END
+WHERE token_hash IS NULL
+ OR token_prefix IS NULL;
+
+ALTER TABLE public.bot_tokens
+ ALTER COLUMN token_hash SET NOT NULL,
+ ALTER COLUMN token_prefix SET NOT NULL;
+
+CREATE UNIQUE INDEX bot_tokens_token_hash_idx
+ ON public.bot_tokens (token_hash);
+
+DROP INDEX public.bot_tokens_token_idx;
+
+ALTER TABLE public.bot_tokens
+ DROP COLUMN token;
diff --git a/packages/sdk/generated/storage/types.gen.ts b/packages/sdk/generated/storage/types.gen.ts
index 528f86ee70..d22bef1340 100644
--- a/packages/sdk/generated/storage/types.gen.ts
+++ b/packages/sdk/generated/storage/types.gen.ts
@@ -1135,9 +1135,9 @@ export type BotToken = {
*/
revoked_at?: string | null;
/**
- * Raw bearer token.
+ * Display prefix of the bearer token. The raw secret is never stored here.
*/
- token: string;
+ token_prefix: string;
};
/**
diff --git a/packages/sdk/specs/storage.json b/packages/sdk/specs/storage.json
index 07eab5243f..98414b7d52 100644
--- a/packages/sdk/specs/storage.json
+++ b/packages/sdk/specs/storage.json
@@ -12762,7 +12762,7 @@
"BotToken": {
"type": "object",
"description": "Bot token metadata.",
- "required": ["id", "bot_id", "token", "created_at"],
+ "required": ["id", "bot_id", "token_prefix", "created_at"],
"properties": {
"bot_id": {
"$ref": "#/components/schemas/BotId",
@@ -12797,9 +12797,9 @@
"format": "date-time",
"description": "Revocation timestamp."
},
- "token": {
+ "token_prefix": {
"type": "string",
- "description": "Raw bearer token."
+ "description": "Display prefix of the bearer token. The raw secret is never stored here."
}
}
},