Skip to content

知了 Cicada · 任何会议和直播的实时字幕、同声传译、AI 会议纪要,Mac、Windows、Linux、Android 免费开源。Live subtitles, interpreting and meeting notes for any call or stream, on Mac, Windows, Linux and Android.

feat(windows): share a meeting as a link, checked for keys and other sensitive content before upload

wquguruad6b596162f2
diff --git a/windows/README.md b/windows/README.md
index 8e3fb0a..5b3c00a 100644
--- a/windows/README.md
+++ b/windows/README.md
@@ -7,6 +7,7 @@ Cicada 的 Windows 版:把电脑播放的声音变成双语字幕和实时纪
- 改正听错的词:和 Mac 版同样的规则和提示词(读音相近才直接改,拼音用 `src/Cicada.Core/Data/pinyin.tsv`,由 Apple 的 ICU/CLDR 汉字转拼音一次生成;新名字先问;词表 `vocabulary.json` 和 Mac 同格式)。Ming 一次给出原文和译文,没有单独的文字翻译请求可搭,所以开着时每句话会多发一次文字请求。没有声音也能试:`cicadactl silentlisten zh-CN`,再 `heard <一句话>`。
- 纪要、记录格式、提示词、多语言文案都和 Mac 版一致;文案的英日韩翻译直接用 `Resources/*.lproj/Localizable.strings`,Windows 独有的在 `src/Cicada/Strings/`。
- 新版本:启动时和每 4 小时查一次 GitHub Releases(`UpdateChecker`),只认带 Windows 安装包的发布;有新版本时托盘图标出现红点、每个版本发一次通知(正在听时等会议结束),托盘面板和设置 › 关于也会提示。点“安装”由知了自己下载这台电脑对应架构的 `Cicada-<版本>-Windows-x64.exe` / `-ARM64.exe`(1.1.0 只认 `Cicada-Setup.exe` 这两个旧名字,发布时一并附上)、对照 `checksums.txt` 校验后安装并重新打开,不经过浏览器,所以 SmartScreen 不拦。开发版只在设了 `CICADA_UPDATE_FEED` 或用 `updatefeed` 调试命令时才查。
+- 分享:会议记录里的“分享…”把纪要(或纪要和双语全文)变成 cicada.indaloop.app 上的链接,分享文档和 Mac 版逐字节相同;上传前服务器检查有没有密钥等敏感内容。设备密钥是 Ed25519(.NET 没有自带,`Cicada.Core/Ed25519.cs` 按 RFC 8032 实现,用 RFC 的测试向量验证),它和每个链接的管理令牌、密码都用 DPAPI 封存在 `share-device.json` 和 `Shares\` 里,不进会议记录、导出和日志。
## 目录
diff --git a/windows/scripts/cicadactl.ps1 b/windows/scripts/cicadactl.ps1
index d46b1d4..a2c50a1 100644
--- a/windows/scripts/cicadactl.ps1
+++ b/windows/scripts/cicadactl.ps1
@@ -4,6 +4,8 @@
# AI 服务检查: ai-check | ai-check-sim <unreachable|invalidKey|noCredit|mgmtKey|noModel|noJSON|deaf|busy|serverError|lowBalance|off> (state › ai.check: every step)
# 结束会议: calls zoom.exe=Zoom|none|real | realcalls | endtimes <silence> <countdown> <grace>|off | endkeep
# 改正听错的词: silentlisten zh-CN | heard <text> | fixstate | fixanswer yes|no | fixlater | fixrevert <line> | fixedit <line>=<text>[|one][|keep0] | fixundo | vocabadd Morpho=莫拉 | vocabstate (… @<id> for another meeting)
+# 分享…: share "<id>[,full][,pw]" | unshare <id> | sharesheet "<id>[,full][,pw][,names][,30|365][,go]" | sharesheet leaveout | sharesheet | shareinfo <id>
+# (quote anything with a comma: PowerShell would make it a list)
param([Parameter(ValueFromRemainingArguments = $true)][string[]]$Command)
$pipe = New-Object System.IO.Pipes.NamedPipeClientStream(".", "cicada-dev", [System.IO.Pipes.PipeDirection]::InOut)
$pipe.Connect(3000)
diff --git a/windows/src/Cicada.Core/Ed25519.cs b/windows/src/Cicada.Core/Ed25519.cs
new file mode 100644
index 0000000..ee36341
--- /dev/null
+++ b/windows/src/Cicada.Core/Ed25519.cs
@@ -0,0 +1,137 @@
+using System.Numerics;
+using System.Security.Cryptography;
+
+namespace Cicada;
+
+/// Ed25519 signatures (RFC 8032 §5.1), for the share service's device key. .NET 10 has no Ed25519
+/// of its own (only inside composite ML-DSA) and Windows CNG can't sign with it, so this is the
+/// RFC's reference algorithm over BigInteger with the built-in SHA-512, checked against the RFC's
+/// test vectors. Not constant-time: the key only names this install to the share service (rate
+/// limits, owning its shares), and anyone can make a new one, so a local timing attack gains nothing.
+public static class Ed25519
+{
+ static readonly BigInteger P = BigInteger.Pow(2, 255) - 19;
+ static readonly BigInteger L = BigInteger.Pow(2, 252) + BigInteger.Parse("27742317777372353535851937790883648493");
+ static readonly BigInteger D = Mod(-121665 * Inv(121666));
+ static readonly BigInteger SqrtM1 = BigInteger.ModPow(2, (P - 1) / 4, P);
+ static readonly Point G = Base();
+
+ readonly record struct Point(BigInteger X, BigInteger Y, BigInteger Z, BigInteger T);
+
+ static BigInteger Mod(BigInteger x) { var r = x % P; return r.Sign < 0 ? r + P : r; }
+ static BigInteger Inv(BigInteger x) => BigInteger.ModPow(x, P - 2, P);
+
+ static Point Base()
+ {
+ var y = Mod(4 * Inv(5));
+ var x = RecoverX(y, 0)!.Value;
+ return new(x, y, 1, Mod(x * y));
+ }
+
+ static Point Add(Point p, Point q)
+ {
+ var a = Mod((p.Y - p.X) * (q.Y - q.X));
+ var b = Mod((p.Y + p.X) * (q.Y + q.X));
+ var c = Mod(2 * p.T * q.T * D);
+ var d = Mod(2 * p.Z * q.Z);
+ BigInteger e = b - a, f = d - c, g = d + c, h = b + a;
+ return new(Mod(e * f), Mod(g * h), Mod(f * g), Mod(e * h));
+ }
+
+ static Point Multiply(BigInteger s, Point p)
+ {
+ var q = new Point(0, 1, 1, 0);
+ while (s > 0)
+ {
+ if (!s.IsEven) q = Add(q, p);
+ p = Add(p, p);
+ s >>= 1;
+ }
+ return q;
+ }
+
+ static bool Same(Point p, Point q) =>
+ Mod(p.X * q.Z - q.X * p.Z) == 0 && Mod(p.Y * q.Z - q.Y * p.Z) == 0;
+
+ static BigInteger? RecoverX(BigInteger y, int sign)
+ {
+ if (y >= P) return null;
+ var x2 = Mod((y * y - 1) * Inv(D * y * y + 1));
+ if (x2 == 0) return sign == 1 ? null : 0;
+ var x = BigInteger.ModPow(x2, (P + 3) / 8, P);
+ if (Mod(x * x - x2) != 0) x = Mod(x * SqrtM1);
+ if (Mod(x * x - x2) != 0) return null;
+ if ((int)(x & 1) != sign) x = P - x;
+ return x;
+ }
+
+ static byte[] Compress(Point p)
+ {
+ var zi = Inv(p.Z);
+ var x = Mod(p.X * zi);
+ var y = Mod(p.Y * zi);
+ var b = Bytes(y);
+ b[31] |= (byte)((int)(x & 1) << 7);
+ return b;
+ }
+
+ static Point? Decompress(ReadOnlySpan<byte> s)
+ {
+ if (s.Length != 32) return null;
+ var copy = s.ToArray();
+ int sign = copy[31] >> 7;
+ copy[31] &= 0x7F;
+ var y = Number(copy);
+ if (RecoverX(y, sign) is not { } x) return null;
+ return new(x, y, 1, Mod(x * y));
+ }
+
+ static BigInteger Number(ReadOnlySpan<byte> le) => new(le, isUnsigned: true, isBigEndian: false);
+
+ static byte[] Bytes(BigInteger n)
+ {
+ var raw = n.ToByteArray(isUnsigned: true, isBigEndian: false);
+ var b = new byte[32];
+ raw.AsSpan(0, Math.Min(32, raw.Length)).CopyTo(b);
+ return b;
+ }
+
+ static (BigInteger a, byte[] prefix) Expand(ReadOnlySpan<byte> seed)
+ {
+ if (seed.Length != 32) throw new ArgumentException("an Ed25519 private key is 32 bytes");
+ var h = SHA512.HashData(seed);
+ h[0] &= 248; h[31] &= 127; h[31] |= 64;
+ return (Number(h.AsSpan(0, 32)), h[32..]);
+ }
+
+ static BigInteger Hash(params byte[][] parts)
+ {
+ using var sha = IncrementalHash.CreateHash(HashAlgorithmName.SHA512);
+ foreach (var p in parts) sha.AppendData(p);
+ return Number(sha.GetHashAndReset()) % L;
+ }
+
+ /// A new private key (the 32-byte seed RFC 8032 calls the secret key).
+ public static byte[] NewKey() => RandomNumberGenerator.GetBytes(32);
+
+ public static byte[] PublicKey(ReadOnlySpan<byte> seed) => Compress(Multiply(Expand(seed).a, G));
+
+ public static byte[] Sign(ReadOnlySpan<byte> seed, byte[] message)
+ {
+ var (a, prefix) = Expand(seed);
+ var pub = Compress(Multiply(a, G));
+ var r = Hash(prefix, message);
+ var rs = Compress(Multiply(r, G));
+ var s = (r + Hash(rs, pub, message) * a) % L;
+ return [.. rs, .. Bytes(s)];
+ }
+
+ public static bool Verify(ReadOnlySpan<byte> publicKey, byte[] message, ReadOnlySpan<byte> signature)
+ {
+ if (signature.Length != 64 || Decompress(publicKey) is not { } a || Decompress(signature[..32]) is not { } r) return false;
+ var s = Number(signature[32..]);
+ if (s >= L) return false;
+ var h = Hash(signature[..32].ToArray(), publicKey.ToArray(), message);
+ return Same(Multiply(s, G), Add(r, Multiply(h, a)));
+ }
+}
diff --git a/windows/src/Cicada.Core/Share.cs b/windows/src/Cicada.Core/Share.cs
new file mode 100644
index 0000000..c7261e7
--- /dev/null
+++ b/windows/src/Cicada.Core/Share.cs
@@ -0,0 +1,575 @@
+using System.Globalization;
+using System.Net;
+using System.Net.Http.Headers;
+using System.Security.Cryptography;
+using System.Text;
+using System.Text.Json;
+using System.Text.Json.Nodes;
+using System.Text.Json.Serialization;
+
+namespace Cicada;
+
+// 分享…: a meeting as a link on cicada.indaloop.app, as on the Mac (ShareProjection.swift,
+// ShareClient.swift). Only the share document leaves the computer, the same bytes the Mac makes
+// (Tests/fixtures/share); server/src/doc.js reads exactly these fields.
+
+public enum ShareScope { Notes, Full }
+
+/// The share document (v1). Never the record's file paths, Ling's guesses at names with the lines
+/// they came from, or the record's own bookkeeping. Speakers are 说话人 N unless names are asked for.
+public sealed record ShareDoc(string Title, string StartedAt, int Duration, List<string> Langs, ShareDoc.NotesPart? Notes, List<ShareDoc.Line> Lines, int Hidden)
+{
+ public sealed record Line(double T, string Who, string Src, string? Dst);
+ public sealed record Topic(double Start, string Title, string Summary, List<string> Points);
+ public sealed record Item(string Text, string? Owner, double? T);
+ public sealed record Term(string Name, string Note);
+ public sealed record NotesPart(string Summary, List<Topic> Topics, List<Item> Conclusions, List<Item> Todos, List<Term> Terms);
+}
+
+public static class ShareProjection
+{
+ /// `removed`: indices into the record's lines the user took out; `dropNotes` leaves the notes out.
+ public static ShareDoc Doc(Session s, ShareScope scope, bool names, ISet<int>? removed = null, bool dropNotes = false)
+ {
+ removed ??= new HashSet<int>();
+ // Not gated on 说话人识别, as on the Mac: the numbers come from the record's voices.
+ var numbers = SpeakerLabels.Numbers(s.Lines);
+ var nameMap = names ? SpeakerLabels.Names(s) : [];
+ string Who(TranscriptLine l)
+ {
+ if (l.Speaker == "me") return Strings.L("分享者");
+ if (!numbers.TryGetValue(l.Id, out var n)) return Strings.L("对方");
+ return names && nameMap.TryGetValue(n, out var name) ? name : Strings.LF("说话人 %lld", n);
+ }
+ var lines = new List<ShareDoc.Line>();
+ if (scope == ShareScope.Full)
+ for (int i = 0; i < s.Lines.Count; i++)
+ {
+ var l = s.Lines[i];
+ if (removed.Contains(i) || l.Src.Length == 0) continue;
+ var dst = string.IsNullOrEmpty(l.Dst) || l.Dst == l.Src ? null : l.Dst;
+ lines.Add(new(Round(l.T), Who(l), l.Src, dst));
+ }
+ ShareDoc.NotesPart? notes = null;
+ if (!dropNotes && s.Notes is { IsEmpty: false } n)
+ {
+ string Swap(string text) => names ? Named(text, nameMap) : text;
+ notes = new(Swap(n.Summary),
+ [.. n.Topics.Select(t => new ShareDoc.Topic(Round(t.Start), Swap(t.Title), Swap(t.Summary), [.. t.Points.Select(Swap)]))],
+ [.. n.Conclusions.Select(c => new ShareDoc.Item(Swap(c.Text), null, c.T is { } t ? Round(t) : null))],
+ [.. n.Todos.Select(c => new ShareDoc.Item(Swap(c.Text), names && c.Owner is { } o ? Swap(o) : null, c.T is { } t ? Round(t) : null))],
+ names ? [.. n.Terms.Select(t => new ShareDoc.Term(t.Name, t.Note))] : []);
+ }
+ var hidden = (scope == ShareScope.Full ? removed.Count : 0) + (dropNotes && s.Notes is { IsEmpty: false } ? 1 : 0);
+ var started = s.StartedAt.ToUniversalTime().ToString("yyyy-MM-dd'T'HH:mm:ss'Z'", CultureInfo.InvariantCulture);
+ return new(SessionStore.DisplayTitle(s), started, (int)Math.Round(s.Duration.TotalSeconds, MidpointRounding.AwayFromZero),
+ Languages(s.Lines), notes, lines, hidden);
+ }
+
+ /// The record lines a full share sends, in order: the server's line numbers index this list.
+ public static List<int> Kept(Session s, ShareScope scope, ISet<int> removed) =>
+ scope == ShareScope.Full ? [.. Enumerable.Range(0, s.Lines.Count).Where(i => !removed.Contains(i) && s.Lines[i].Src.Length > 0)] : [];
+
+ /// The meeting's usual direction ("en" → "zh"), by the most lines; ties go to the earliest.
+ public static List<string> Languages(IReadOnlyList<TranscriptLine> lines)
+ {
+ var count = new Dictionary<string, int>();
+ var first = new Dictionary<string, int>();
+ for (int i = 0; i < lines.Count; i++)
+ {
+ var l = lines[i];
+ if (l.Dst is null) continue;
+ var key = Base(l.SrcLang) + ">" + Base(l.DstLang);
+ count[key] = count.GetValueOrDefault(key) + 1;
+ first.TryAdd(key, i);
+ }
+ if (count.Count == 0) return [];
+ var top = count.Keys.OrderByDescending(k => count[k]).ThenBy(k => first[k]).First();
+ return [.. top.Split('>')];
+ }
+
+ static string Base(string code) => (code.Split('-', StringSplitOptions.RemoveEmptyEntries).FirstOrDefault() ?? code).ToLowerInvariant();
+
+ /// One decimal, rounded half away from zero as Swift's `rounded()`: the same bytes everywhere.
+ static double Round(double t) => Math.Round(t * 10, MidpointRounding.AwayFromZero) / 10;
+
+ /// Ling wrote "说话人 6" before anyone named them: the name since given (SpeakerLabels.named).
+ public static string Named(string text, IReadOnlyDictionary<int, string> names)
+ {
+ if (names.Count == 0 || !(text.Contains("说话人") || text.Contains("Speaker"))) return text;
+ foreach (var (n, name) in names.OrderByDescending(kv => kv.Key)) // 说话人 12 before 说话人 1
+ foreach (var form in new[] { $"说话人 {n}", $"说话人{n}", $"Speaker {n}" })
+ text = text.Replace(form, name, StringComparison.Ordinal);
+ return text;
+ }
+
+ /// Compact, sorted keys, slashes unescaped, whole numbers without ".0": Swift's JSONEncoder with
+ /// [.sortedKeys, .withoutEscapingSlashes], written by hand so no encoder default can drift.
+ public static string Encode(ShareDoc d)
+ {
+ var b = new StringBuilder();
+ b.Append("{\"duration\":").Append(d.Duration.ToString(CultureInfo.InvariantCulture));
+ b.Append(",\"hidden\":").Append(d.Hidden.ToString(CultureInfo.InvariantCulture));
+ b.Append(",\"langs\":"); List(b, d.Langs, Str);
+ b.Append(",\"lines\":"); List(b, d.Lines, (b, l) =>
+ {
+ b.Append('{');
+ if (l.Dst is not null) { b.Append("\"dst\":"); Str(b, l.Dst); b.Append(','); }
+ b.Append("\"src\":"); Str(b, l.Src);
+ b.Append(",\"t\":"); Num(b, l.T);
+ b.Append(",\"who\":"); Str(b, l.Who);
+ b.Append('}');
+ });
+ if (d.Notes is { } n)
+ {
+ b.Append(",\"notes\":{\"conclusions\":"); List(b, n.Conclusions, ItemJson);
+ b.Append(",\"summary\":"); Str(b, n.Summary);
+ b.Append(",\"terms\":"); List(b, n.Terms, (b, t) => { b.Append("{\"name\":"); Str(b, t.Name); b.Append(",\"note\":"); Str(b, t.Note); b.Append('}'); });
+ b.Append(",\"todos\":"); List(b, n.Todos, ItemJson);
+ b.Append(",\"topics\":"); List(b, n.Topics, (b, t) =>
+ {
+ b.Append("{\"points\":"); List(b, t.Points, Str);
+ b.Append(",\"start\":"); Num(b, t.Start);
+ b.Append(",\"summary\":"); Str(b, t.Summary);
+ b.Append(",\"title\":"); Str(b, t.Title);
+ b.Append('}');
+ });
+ b.Append('}');
+ }
+ b.Append(",\"startedAt\":"); Str(b, d.StartedAt);
+ b.Append(",\"title\":"); Str(b, d.Title);
+ b.Append(",\"v\":1}");
+ return b.ToString();
+ }
+
+ static void ItemJson(StringBuilder b, ShareDoc.Item i)
+ {
+ b.Append('{');
+ if (i.Owner is not null) { b.Append("\"owner\":"); Str(b, i.Owner); b.Append(','); }
+ if (i.T is { } t) { b.Append("\"t\":"); Num(b, t); b.Append(','); }
+ b.Append("\"text\":"); Str(b, i.Text);
+ b.Append('}');
+ }
+
+ static void List<T>(StringBuilder b, IEnumerable<T> items, Action<StringBuilder, T> each)
+ {
+ b.Append('[');
+ bool first = true;
+ foreach (var x in items) { if (!first) b.Append(','); first = false; each(b, x); }
+ b.Append(']');
+ }
+
+ /// Shortest round-trip text; a whole number has no fraction (605, not 605.0).
+ static void Num(StringBuilder b, double v) => b.Append(v.ToString("R", CultureInfo.InvariantCulture));
+
+ /// As Swift escapes: quote, backslash and control characters only; everything else as is.
+ static void Str(StringBuilder b, string s)
+ {
+ b.Append('"');
+ foreach (var c in s)
+ switch (c)
+ {
+ case '"': b.Append("\\\""); break;
+ case '\\': b.Append("\\\\"); break;
+ case '\n': b.Append("\\n"); break;
+ case '\r': b.Append("\\r"); break;
+ case '\t': b.Append("\\t"); break;
+ case '\b': b.Append("\\b"); break;
+ case '\f': b.Append("\\f"); break;
+ case < ' ': b.Append("\\u").Append(((int)c).ToString("x4", CultureInfo.InvariantCulture)); break;
+ default: b.Append(c); break;
+ }
+ b.Append('"');
+ }
+}
+
+/// A meeting shared as a link: what this computer keeps about it. The manage token (needed to turn
+/// the link off) and the password live only in Shares/<record id>.json, sealed like the AI keys,
+/// never in the record, exports or logs.
+public sealed class ShareRecord
+{
+ [JsonPropertyName("createdAt")] public DateTimeOffset CreatedAt { get; set; }
+ [JsonPropertyName("expiresAt")] public DateTimeOffset ExpiresAt { get; set; }
+ [JsonPropertyName("id")] public string Id { get; set; } = "";
+ [JsonPropertyName("password")] public string? Password { get; set; }
+ [JsonPropertyName("scope")] public string Scope { get; set; } = "notes";
+ [JsonPropertyName("token")] public string Token { get; set; } = "";
+ [JsonPropertyName("url")] public string Url { get; set; } = "";
+}
+
+/// Where the review found a problem: the notes, or lines `from`…`to` of what was sent.
+public sealed record ShareHit(
+ [property: JsonPropertyName("part")] string Part,
+ [property: JsonPropertyName("from")] int? From,
+ [property: JsonPropertyName("to")] int? To,
+ [property: JsonPropertyName("questions")] List<string> Questions)
+{
+ /// The record's line indices behind the hits, given which record lines were sent (`kept`).
+ public static HashSet<int> RecordLines(IEnumerable<ShareHit> hits, IReadOnlyList<int> kept)
+ {
+ var outp = new HashSet<int>();
+ foreach (var h in hits)
+ {
+ if (h.Part != "lines" || h.From is not { } a || h.To is not { } b || a > b) continue;
+ for (int i = Math.Max(0, a); i <= b && i < kept.Count; i++) outp.Add(kept[i]);
+ }
+ return outp;
+ }
+}
+
+public static class SharePassword
+{
+ public const int Iterations = 210_000;
+
+ /// PBKDF2-SHA256, 32 bytes: what the browser derives from the password (site/share.js). The
+ /// server keeps only its hash, so the password itself never leaves either side.
+ public static byte[] Verifier(string password, byte[] salt, int iterations = Iterations) =>
+ Rfc2898DeriveBytes.Pbkdf2(Encoding.UTF8.GetBytes(password), salt, iterations, HashAlgorithmName.SHA256, 32);
+
+ /// "ruby-41-lake": easy to read out and type; the server limits how many can be tried.
+ public static string Make()
+ {
+ var w = Words.Split(' ');
+ return $"{w[RandomNumberGenerator.GetInt32(w.Length)]}-{RandomNumberGenerator.GetInt32(10, 100)}-{w[RandomNumberGenerator.GetInt32(w.Length)]}";
+ }
+
+ const string Words = "amber apple arrow aspen basil beach birch bloom brook cedar cherry cloud coral comet dawn delta dune ember fern field flint frost grove harbor hazel honey iris island jade lake lark lemon lily linen maple meadow mint moss olive orbit pearl pine plum pond quartz rain reed river ruby sage sand shell silk sky slate snow spruce stone storm sun tide tulip velvet willow wind";
+}
+
+/// A file only this user can read: DPAPI-sealed on Windows ("dpapi:" + base64, as AIKey), 0600 elsewhere.
+public static class SecretFile
+{
+ public static bool Write(IKeyProtector protector, string path, string text)
+ {
+ try
+ {
+ Directory.CreateDirectory(Path.GetDirectoryName(path)!);
+ var body = protector.Tag == "plain" ? text : "dpapi:" + Convert.ToBase64String(protector.Protect(Encoding.UTF8.GetBytes(text)));
+ if (!OperatingSystem.IsWindows())
+ {
+ using (File.Create(path, 1, FileOptions.None)) { }
+ File.SetUnixFileMode(path, UnixFileMode.UserRead | UnixFileMode.UserWrite);
+ }
+ File.WriteAllText(path, body);
+ return true;
+ }
+ catch (Exception e)
+ {
+ Log.Debug($"share: could not write {Path.GetFileName(path)} {e.GetType().Name}");
+ return false;
+ }
+ }
+
+ public static string? Read(IKeyProtector protector, string path)
+ {
+ try
+ {
+ if (!File.Exists(path)) return null;
+ var text = File.ReadAllText(path).Trim();
+ return text.StartsWith("dpapi:") ? Encoding.UTF8.GetString(protector.Unprotect(Convert.FromBase64String(text["dpapi:".Length..]))) : text;
+ }
+ catch (Exception e)
+ {
+ Log.Debug($"share: could not read {Path.GetFileName(path)} {e.GetType().Name}");
+ return null;
+ }
+ }
+}
+
+/// Shares/<record id>.json, sealed.
+public sealed class ShareStore(IKeyProtector protector, string? folder = null)
+{
+ public string Folder => folder ?? Path.Combine(Paths.Root, "Shares");
+ string FileOf(string sessionId) => Path.Combine(Folder, sessionId + ".json");
+
+ public ShareRecord? Read(string sessionId)
+ {
+ if (SecretFile.Read(protector, FileOf(sessionId)) is not { } text) return null;
+ try { return Json.Read<ShareRecord>(text); } catch { return null; }
+ }
+
+ public void Save(ShareRecord r, string sessionId) => SecretFile.Write(protector, FileOf(sessionId), JsonSerializer.Serialize(r, Json.Compact));
+
+ public void Remove(string sessionId) { try { File.Delete(FileOf(sessionId)); } catch { } }
+
+ public Dictionary<string, ShareRecord> All()
+ {
+ var outp = new Dictionary<string, ShareRecord>();
+ if (!Directory.Exists(Folder)) return outp;
+ foreach (var f in Directory.GetFiles(Folder, "*.json"))
+ {
+ var id = Path.GetFileNameWithoutExtension(f);
+ if (Read(id) is { } r) outp[id] = r;
+ }
+ return outp;
+ }
+}
+
+public sealed record ShareOptions
+{
+ public ShareScope Scope { get; init; } = ShareScope.Notes;
+ public int Days { get; init; } = 7;
+ public bool Names { get; init; }
+ public string? Password { get; init; }
+ public bool SummaryInPreview { get; init; }
+ public HashSet<int> Removed { get; init; } = [];
+ public bool DropNotes { get; init; }
+}
+
+public abstract record ShareOutcome
+{
+ public sealed record Shared(ShareRecord Record) : ShareOutcome;
+ public sealed record Blocked(List<ShareHit> Hits, List<int> Kept) : ShareOutcome;
+ public sealed record Failed(string Code, int? RetryAfter) : ShareOutcome;
+}
+
+/// Talks to the share service (server/). No accounts: this install is an Ed25519 key made on first
+/// use (share-device.json, sealed), registered once with a small proof of work, and every write is
+/// signed (method, path, time, nonce, body hash), as server/src/auth.js checks. Not an AI call, so
+/// not LingClient: the review runs on the server.
+public sealed class ShareClient
+{
+ readonly IKeyProtector protector;
+ readonly string platform, version;
+ readonly HttpClient http;
+ readonly SemaphoreSlim registering = new(1, 1);
+ public ShareStore Store { get; }
+
+ public ShareClient(IKeyProtector protector, string platform, string version, HttpMessageHandler? handler = null, string? folder = null)
+ {
+ this.protector = protector; this.platform = platform; this.version = version;
+ http = new HttpClient(handler ?? new HttpClientHandler()) { Timeout = TimeSpan.FromSeconds(90) };
+ root = folder;
+ Store = new ShareStore(protector, folder is null ? null : Path.Combine(folder, "Shares"));
+ }
+
+ readonly string? root;
+
+ /// A dev build can point at a local Worker: CICADA_SHARE_SERVER=http://127.0.0.1:8787.
+ public Uri Base => Environment.GetEnvironmentVariable("CICADA_SHARE_SERVER") is { Length: > 0 } s && Uri.TryCreate(s, UriKind.Absolute, out var u)
+ ? u : new Uri("https://cicada.indaloop.app");
+
+ string DeviceFile => Path.Combine(root ?? Paths.Root, "share-device.json");
+
+ sealed class Device
+ {
+ [JsonPropertyName("device")] public string? Id { get; set; }
+ [JsonPropertyName("key")] public string Key { get; set; } = "";
+ [JsonPropertyName("server")] public string? Server { get; set; }
+ }
+
+ Device LoadDevice()
+ {
+ if (SecretFile.Read(protector, DeviceFile) is { } text)
+ try
+ {
+ if (Json.Read<Device>(text) is { } d && Convert.FromBase64String(d.Key).Length == 32) return d;
+ }
+ catch { }
+ var f = new Device { Key = Convert.ToBase64String(Ed25519.NewKey()) };
+ SaveDevice(f);
+ return f;
+ }
+
+ void SaveDevice(Device d) => SecretFile.Write(protector, DeviceFile, JsonSerializer.Serialize(d, Json.Compact));
+
+ /// The key and device id, registering this install with the server first if needed. One at a
+ /// time: the server allows only a few registrations a day from one address.
+ async Task<(byte[] key, string id)> Registered(bool force = false)
+ {
+ await registering.WaitAsync();
+ try
+ {
+ var d = LoadDevice();
+ var key = Convert.FromBase64String(d.Key);
+ if (!force && d.Id is { } known && d.Server == Base.AbsoluteUri) return (key, known);
+ var watch = System.Diagnostics.Stopwatch.StartNew();
+ var pub = Ed25519.PublicKey(key);
+ var nonce = await Task.Run(() => ProofOfWork(pub));
+ Log.Debug($"share: proof of work in {watch.ElapsedMilliseconds} ms");
+ var body = new JsonObject { ["key"] = B64Url(pub), ["pow"] = B64Url(nonce), ["platform"] = platform, ["version"] = version }.ToJsonString();
+ var (data, status) = await Send("POST", "/api/v1/devices", body, null, null);
+ var id = status == 201 ? Field(data, "device") : null;
+ if (id is null)
+ {
+ Log.Debug($"share: register failed {status} {Field(data, "code") ?? "?"}");
+ throw new Failure(Field(data, "code") ?? "register_failed", RetryAfter(data));
+ }
+ d.Id = id; d.Server = Base.AbsoluteUri;
+ SaveDevice(d);
+ Log.Debug("share: device registered");
+ return (key, id);
+ }
+ finally { registering.Release(); }
+ }
+
+ /// 20 leading zero bits of sha256(public key ‖ 8-byte big-endian nonce): about a million hashes.
+ public static byte[] ProofOfWork(byte[] pub)
+ {
+ var work = new byte[pub.Length + 8];
+ pub.CopyTo(work, 0);
+ Span<byte> h = stackalloc byte[32];
+ for (ulong n = 0; ; n++)
+ {
+ System.Buffers.Binary.BinaryPrimitives.WriteUInt64BigEndian(work.AsSpan(pub.Length), n);
+ SHA256.HashData(work, h);
+ if (h[0] == 0 && h[1] == 0 && h[2] < 16) return work[pub.Length..];
+ }
+ }
+
+ sealed class Failure(string code, int? retryAfter) : Exception
+ {
+ public string Code { get; } = code;
+ public int? RetryAfter { get; } = retryAfter;
+ }
+
+ async Task<(string body, int status)> Send(string method, string path, string? body, Dictionary<string, string>? headers, (byte[] key, string id)? signer)
+ {
+ using var req = new HttpRequestMessage(new HttpMethod(method), new Uri(Base, path));
+ if (body is not null) req.Content = new StringContent(body, Encoding.UTF8, "application/json");
+ req.Headers.TryAddWithoutValidation("X-Cicada-Client", $"{platform}/{version}");
+ foreach (var (k, v) in headers ?? []) req.Headers.TryAddWithoutValidation(k, v);
+ if (signer is var (key, id))
+ {
+ var time = DateTimeOffset.UtcNow.ToUnixTimeSeconds().ToString(CultureInfo.InvariantCulture);
+ var nonce = B64Url(RandomNumberGenerator.GetBytes(16));
+ var hash = Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(body ?? "")));
+ // The path as it goes on the wire, query included, so the server's URL reads the same.
+ var message = $"{method}\n{req.RequestUri!.PathAndQuery}\n{time}\n{nonce}\n{hash}";
+ req.Headers.TryAddWithoutValidation("X-Cicada-Device", id);
+ req.Headers.TryAddWithoutValidation("X-Cicada-Time", time);
+ req.Headers.TryAddWithoutValidation("X-Cicada-Nonce", nonce);
+ req.Headers.TryAddWithoutValidation("X-Cicada-Signature", B64Url(Ed25519.Sign(key, Encoding.UTF8.GetBytes(message))));
+ }
+ try
+ {
+ using var resp = await http.SendAsync(req);
+ return (await resp.Content.ReadAsStringAsync(), (int)resp.StatusCode);
+ }
+ catch (Exception e)
+ {
+ Log.Debug($"share: {method} failed {e.GetType().Name}");
+ throw new Failure("network", null);
+ }
+ }
+
+ /// A signed call; registers again once if the server no longer knows this install.
+ async Task<(string body, int status)> Signed(string method, string path, string? body = null, Dictionary<string, string>? headers = null)
+ {
+ var signer = await Registered();
+ var (data, status) = await Send(method, path, body, headers, signer);
+ if (status == 401 && Field(data, "code") == "unknown_device")
+ {
+ signer = await Registered(force: true);
+ (data, status) = await Send(method, path, body, headers, signer);
+ }
+ return (data, status);
+ }
+
+ /// Never throws: the dialog awaits it from an event handler.
+ public async Task<ShareOutcome> Share(Session s, ShareOptions o)
+ {
+ try { return await Attempt(s, o); }
+ catch (Exception e)
+ {
+ Log.Debug($"share: {e.GetType().Name}");
+ return new ShareOutcome.Failed("server_error", null);
+ }
+ }
+
+ async Task<ShareOutcome> Attempt(Session s, ShareOptions o)
+ {
+ var doc =ShareProjection.Encode(ShareProjection.Doc(s, o.Scope, o.Names, o.Removed, o.DropNotes));
+ var kept = ShareProjection.Kept(s, o.Scope, o.Removed);
+ var scope = o.Scope == ShareScope.Full ? "full" : "notes";
+ var body = new JsonObject
+ {
+ ["doc"] = JsonNode.Parse(doc), ["scope"] = scope, ["days"] = o.Days, ["summaryInPreview"] = o.SummaryInPreview,
+ };
+ if (o.Password is { } pw)
+ {
+ var salt = RandomNumberGenerator.GetBytes(16);
+ var v = await Task.Run(() => SharePassword.Verifier(pw, salt));
+ body["password"] = new JsonObject { ["salt"] = B64Url(salt), ["iter"] = SharePassword.Iterations, ["hash"] = B64Url(SHA256.HashData(v)) };
+ }
+ // The same meeting, content and settings sent again (the answer was lost) gets the same link
+ // back; any other setting makes a new share.
+ var settings = $"{scope}|{o.Days}|{(o.Names ? "true" : "false")}|{o.Password ?? ""}|{(o.SummaryInPreview ? "true" : "false")}";
+ var idem = s.Id + "-" + Convert.ToHexStringLower(SHA256.HashData(Encoding.UTF8.GetBytes(doc + settings))[..8]);
+ try
+ {
+ var (data, status) = await Signed("POST", "/api/v1/shares", body.ToJsonString(Json.Compact), new() { ["Idempotency-Key"] = idem });
+ var obj = Parse(data);
+ switch (status)
+ {
+ case 200 or 201:
+ if (obj?["id"]?.GetValue<string>() is not { } id || obj["url"]?.GetValue<string>() is not { } url
+ || obj["token"]?.GetValue<string>() is not { } token || obj["expiresAt"] is not JsonValue exp)
+ return new ShareOutcome.Failed("server_error", null);
+ if (Store.Read(s.Id) is { } old && old.Id != id) await Revoke(old, null);
+ var r = new ShareRecord
+ {
+ Id = id, Url = url, Token = token, ExpiresAt = DateTimeOffset.FromUnixTimeSeconds((long)exp.GetValue<double>()),
+ Scope = scope, Password = o.Password, CreatedAt = DateTimeOffset.UtcNow,
+ };
+ Store.Save(r, s.Id);
+ Log.Debug($"share: {s.Id} shared ({scope}, {o.Days} days{(o.Password is null ? "" : ", password")})");
+ return new ShareOutcome.Shared(r);
+ case 422:
+ var hits = obj?["hits"]?.Deserialize<List<ShareHit>>(Json.Compact) ?? [];
+ Log.Debug($"share: {s.Id} blocked " + string.Join("; ", hits.Select(h => h.Part + (h.From is { } f ? $" {f}-{h.To ?? f}" : "") + " " + string.Join(",", h.Questions))));
+ return new ShareOutcome.Blocked(hits, kept);
+ default:
+ Log.Debug($"share: {s.Id} failed {status} {Field(data, "code") ?? "?"}");
+ return new ShareOutcome.Failed(Field(data, "code") ?? "server_error", RetryAfter(data));
+ }
+ }
+ catch (Failure f) { return new ShareOutcome.Failed(f.Code, f.RetryAfter); }
+ catch (Exception e)
+ {
+ Log.Debug($"share: {e.GetType().Name}");
+ return new ShareOutcome.Failed("server_error", null);
+ }
+ }
+
+ /// Turns the link off on the server and forgets it here. `sessionId` null: it is being replaced.
+ public async Task<bool> Revoke(ShareRecord r, string? sessionId)
+ {
+ bool ok;
+ try
+ {
+ var (data, status) = await Signed("DELETE", "/api/v1/shares/" + r.Id, null, new() { ["Authorization"] = "Bearer " + r.Token });
+ // 404: already gone (or never ours); either way nothing to keep.
+ ok = status is 204 or 404;
+ if (!ok) Log.Debug($"share: revoke failed {status} {Field(data, "code") ?? "?"}");
+ }
+ catch (Exception e) { Log.Debug($"share: revoke {e.GetType().Name}"); ok = false; }
+ if (ok && sessionId is not null) Store.Remove(sessionId);
+ return ok;
+ }
+
+ public sealed record Stats(string Id, double ExpiresAt, string State, int Views);
+
+ public async Task<Dictionary<string, Stats>> StatsOf(IEnumerable<string> ids)
+ {
+ var list = ids.ToList();
+ var outp = new Dictionary<string, Stats>();
+ if (list.Count == 0) return outp;
+ try
+ {
+ var (data, status) = await Signed("GET", "/api/v1/shares?ids=" + string.Join(",", list));
+ if (status != 200 || Parse(data)?["shares"] is not JsonArray shares) return outp;
+ foreach (var x in shares)
+ if (x?["id"]?.GetValue<string>() is { } id)
+ outp[id] = new(id, x["expiresAt"]?.GetValue<double>() ?? 0, x["state"]?.GetValue<string>() ?? "", (int)(x["views"]?.GetValue<double>() ?? 0));
+ }
+ catch (Exception e) { Log.Debug($"share: stats {e.GetType().Name}"); }
+ return outp;
+ }
+
+ public static string B64Url(byte[] d) => Convert.ToBase64String(d).Replace('+', '-').Replace('/', '_').TrimEnd('=');
+
+ static JsonNode? Parse(string text) { try { return JsonNode.Parse(text); } catch { return null; } }
+ static string? Field(string text, string key) { try { return Parse(text)?[key]?.GetValue<string>(); } catch { return null; } }
+ static int? RetryAfter(string text) { try { return Parse(text)?["retryAfter"] is JsonValue v ? (int)v.GetValue<double>() : null; } catch { return null; } }
+}
diff --git a/windows/src/Cicada/App.cs b/windows/src/Cicada/App.cs
index 5206de6..a500e02 100644
--- a/windows/src/Cicada/App.cs
+++ b/windows/src/Cicada/App.cs
@@ -61,6 +61,8 @@ sealed class Controller
public readonly UpdateChecker Updates;
public readonly Vocabulary Vocabulary;
public readonly LiveFixes Fixes;
+ /// 分享…: the share service, its device key and the links made (sealed files, never the record).
+ public readonly ShareClient Sharing = new(new DpapiProtector(), "windows", Version);
/// Dev (`silentlisten`): the language `heard` lines are in.
public string? SilentLang;
/// Started with Windows (--background): stay in the tray. Opened by hand, the main window shows.
@@ -872,6 +874,15 @@ sealed class Controller
public void OpenRecord(string id, string tab) { ShowRecords(id); mainWindow?.Select(id, tab); }
public void Play(string arg) => mainWindow?.DebugPlay(arg);
+ /// 分享…: the dialog over the records window (or the screen's centre without it).
+ public ShareDialog ShareSheet(Session s)
+ {
+ ShareDialog.Current?.Close();
+ var d = new ShareDialog(this, s, mainWindow is { IsVisible: true } ? mainWindow : null);
+ d.Show();
+ return d;
+ }
+
public void ShowRecords(string? id)
{
if (mainWindow is null) { mainWindow = new MainWindow(this, id); mainWindow.Closed += (_, _) => { mainWindow = null; WindowClosed(); }; }
@@ -1389,6 +1400,58 @@ static class DebugServer
case "fixundo": app.Fixes.Undo(); break;
case "fixeditor": { var (id, lineId) = FixTarget(app, arg); app.DebugEditLine(id, lineId); break; } // fixeditor <line> [@id]
case "vocabpaste": app.DebugPaste(arg); break; // vocabpaste <line|line…>: 粘贴导入, filled in, not imported
+ case "share":
+ {
+ // share <record id>[,full][,pw] shares a meeting as the dialog would (CICADA_SHARE_SERVER
+ // points a dev build at a local Worker); unshare <record id> turns it off.
+ var p = arg.Split(',');
+ if (app.Store.Get(p[0]) is not { } s) return new JsonObject { ["error"] = "no such record" };
+ var o = new ShareOptions
+ {
+ Scope = p.Contains("full") || s.Notes is not { IsEmpty: false } ? ShareScope.Full : ShareScope.Notes,
+ Password = p.Contains("pw") ? SharePassword.Make() : null,
+ };
+ _ = Task.Run(async () =>
+ {
+ var r = await app.Sharing.Share(s, o);
+ Log.Debug(r switch
+ {
+ ShareOutcome.Shared x => $"share: {x.Record.Url}",
+ ShareOutcome.Blocked b => $"share: blocked lines {string.Join(",", ShareHit.RecordLines(b.Hits, b.Kept).Order())}{(b.Hits.Any(h => h.Part == "notes") ? " and notes" : "")}",
+ ShareOutcome.Failed f => $"share: failed {f.Code}",
+ _ => "share: ?",
+ });
+ });
+ break;
+ }
+ case "unshare":
+ {
+ if (app.Sharing.Store.Read(arg) is not { } r) return new JsonObject { ["error"] = "not shared" };
+ _ = Task.Run(async () => Log.Debug($"share: revoked {await app.Sharing.Revoke(r, arg)}"));
+ break;
+ }
+ // sharesheet <record id>[,full][,pw][,names][,30|365][,go] opens 分享… (go presses 生成链接);
+ // sharesheet leaveout presses 去掉这些内容后分享; sharesheet alone closes it.
+ case "sharesheet" or "shareSheet":
+ {
+ var p = arg.Split(',', StringSplitOptions.RemoveEmptyEntries);
+ if (p.Length == 0) { ShareDialog.Current?.Close(); break; }
+ if (p[0] == "leaveout") { ShareDialog.Current?.DebugLeaveOut(); break; }
+ if (app.Store.Get(p[0]) is not { } s) return new JsonObject { ["error"] = "no such record" };
+ app.ShowRecords(p[0]);
+ app.Dispatcher().BeginInvoke(() => app.ShareSheet(s).Debug(p));
+ break;
+ }
+ // shareinfo <record id>: the link kept for it (dev builds only, never logged) and the open dialog's step.
+ case "shareinfo":
+ {
+ var r = app.Sharing.Store.Read(arg);
+ return new JsonObject
+ {
+ ["url"] = r?.Url, ["expiresAt"] = r?.ExpiresAt.ToUnixTimeSeconds(), ["scope"] = r?.Scope, ["password"] = r?.Password,
+ ["sheet"] = ShareDialog.Current?.StepName,
+ };
+ }
case "state": break;
default: return new JsonObject { ["error"] = $"unknown command {parts[0]}" };
}
diff --git a/windows/src/Cicada/MainWindow.cs b/windows/src/Cicada/MainWindow.cs
index 407de80..363f11c 100644
--- a/windows/src/Cicada/MainWindow.cs
+++ b/windows/src/Cicada/MainWindow.cs
@@ -516,6 +516,10 @@ sealed class MainWindow : Window
tools.Children.Add(copy);
}
tools.Children.Add(Spaced(Small(Ui.Button(L("导出…"), () => Export(s), Ui.Kind.Standard, height: 32)), 8));
+ // Not while the meeting is still going, nor with nothing in it.
+ var share = Small(Ui.Button(L("分享…"), () => app.ShareSheet(s), Ui.Kind.Standard, height: 32));
+ share.IsEnabled = !live && (s.Lines.Count > 0 || hasNotes);
+ tools.Children.Add(Spaced(share, 8));
Button? more = null;
more = Ui.Button("···", () =>
{
diff --git a/windows/src/Cicada/ShareDialog.cs b/windows/src/Cicada/ShareDialog.cs
new file mode 100644
index 0000000..f37f586
--- /dev/null
+++ b/windows/src/Cicada/ShareDialog.cs
@@ -0,0 +1,382 @@
+using System.Windows;
+using System.Windows.Controls;
+using System.Windows.Input;
+using System.Windows.Media;
+using static Cicada.Strings;
+
+namespace Cicada.App;
+
+/// 分享…: a meeting as a link on cicada.indaloop.app (the Mac's ShareSheet). Settings, then the
+/// server's review, then the link (and its password) or what the review stopped. A meeting already
+/// shared opens on its link. Drawn in the chrome of Dialogs, its content swapped per step.
+sealed class ShareDialog : Window
+{
+ enum Step { Settings, Working, Blocked, Done, Failed }
+
+ readonly Controller app;
+ readonly Session session;
+ readonly ContentControl body = new();
+ Step step = Step.Settings;
+ ShareScope scope = ShareScope.Notes;
+ int days = 7;
+ bool names, usePassword, summaryInPreview, dropNotes, confirmRevoke;
+ string password = SharePassword.Make();
+ readonly HashSet<int> removed = [];
+ List<ShareHit> hits = [];
+ List<int> kept = [];
+ ShareRecord? record;
+ int? views;
+ string? copied, failure;
+
+ bool HasNotes => session.Notes is { IsEmpty: false };
+
+ /// The open one, for the debug pipe (`sharesheet`).
+ public static ShareDialog? Current { get; private set; }
+
+ public ShareDialog(Controller app, Session session, Window? owner)
+ {
+ this.app = app;
+ this.session = session;
+ Owner = owner;
+ WindowStyle = WindowStyle.None; AllowsTransparency = true; Background = Brushes.Transparent;
+ ResizeMode = ResizeMode.NoResize; ShowInTaskbar = false; SizeToContent = SizeToContent.Height; Width = 456 + 32;
+ WindowStartupLocation = owner is null ? WindowStartupLocation.CenterScreen : WindowStartupLocation.CenterOwner;
+ FontFamily = Palette.Font; Title = L("分享这场会议");
+ Content = new Border
+ {
+ Margin = new Thickness(16), Background = Palette.Surface, BorderBrush = Palette.Line, BorderThickness = new Thickness(1), CornerRadius = new CornerRadius(16),
+ Effect = new System.Windows.Media.Effects.DropShadowEffect { BlurRadius = 32, ShadowDepth = 8, Opacity = 0.25 },
+ Padding = new Thickness(24), Child = body,
+ };
+ MouseLeftButtonDown += (_, e) => { if (e.ButtonState == MouseButtonState.Pressed && e.OriginalSource is not TextBox) try { DragMove(); } catch { } };
+ KeyDown += (_, e) => { if (e.Key == Key.Escape && step != Step.Working) Close(); };
+ if (!HasNotes) scope = ShareScope.Full;
+ if (app.Sharing.Store.Read(session.Id) is { } r && r.ExpiresAt > DateTimeOffset.Now) { record = r; step = Step.Done; LoadViews(r); }
+ Loaded += (_, _) => Current = this;
+ Closed += (_, _) => { if (Current == this) Current = null; };
+ Render();
+ }
+
+ void Render()
+ {
+ body.Content = step switch
+ {
+ Step.Settings => SettingsView(),
+ Step.Working => Working(),
+ Step.Blocked => BlockedView(),
+ Step.Done => DoneView(record!),
+ _ => FailedView(),
+ };
+ }
+
+ // MARK: Settings
+
+ UIElement SettingsView()
+ {
+ var p = new StackPanel();
+ p.Children.Add(Header(L("分享这场会议")));
+ p.Children.Add(Gap(Ui.Text(L("内容"), 12, Palette.Secondary, FontWeights.SemiBold), 16));
+ p.Children.Add(Gap(Radio(L("只分享纪要"), scope == ShareScope.Notes, HasNotes, () => scope = ShareScope.Notes), 6));
+ p.Children.Add(Gap(Radio(L("纪要和双语全文"), scope == ShareScope.Full, true, () => scope = ShareScope.Full), 6));
+ p.Children.Add(Gap(Row(L("有效期"), Ui.Choice([("7", L("7 天")), ("30", L("30 天")), ("365", L("1 年"))], days.ToString(), v => days = int.Parse(v), width: 140)), 16));
+ p.Children.Add(Gap(Row(L("显示说话人名字"), Ui.Switch(names, v => names = v, L("显示说话人名字"))), 12));
+ p.Children.Add(Gap(Row(L("用密码保护"), Ui.Switch(usePassword, v => { usePassword = v; Render(); }, L("用密码保护"))), 12));
+ Button? make = null;
+ if (usePassword)
+ {
+ var box = new TextBox { Text = password, FontFamily = new FontFamily("Cascadia Mono, Consolas") };
+ System.Windows.Automation.AutomationProperties.SetName(box, L("用密码保护"));
+ box.TextChanged += (_, _) => { password = box.Text; if (make is not null) make.IsEnabled = password.Trim().Length >= 6; };
+ var again = Ui.Button(L("换一个"), () => { password = SharePassword.Make(); Render(); }, height: 34);
+ again.MinWidth = 0; again.Margin = new Thickness(8, 0, 0, 0);
+ var grid = new DockPanel();
+ DockPanel.SetDock(again, Dock.Right);
+ grid.Children.Add(again); grid.Children.Add(Ui.Field(box));
+ p.Children.Add(Gap(grid, 8));
+ }
+ else if (HasNotes)
+ p.Children.Add(Gap(Row(L("预览卡显示摘要"), Ui.Switch(summaryInPreview, v => summaryInPreview = v, L("预览卡显示摘要"))), 12));
+ p.Children.Add(Gap(Ui.Helper(usePassword ? L("建议把链接和密码分两条消息发送。") : L("内容将上传至 cicada.indaloop.app,拿到链接的人都能看。")), 16));
+ make = Ui.Button(L("生成链接"), Go, Ui.Kind.Primary);
+ make.IsDefault = true;
+ make.IsEnabled = !usePassword || password.Trim().Length >= 6;
+ p.Children.Add(Gap(Buttons(Ui.Button(L("取消"), Close), make), 24));
+ return p;
+ }
+
+ /// Takes the dialog's settings from the debug pipe: `sharesheet <id>[,full][,pw][,names][,30][,go]`.
+ public void Debug(IReadOnlyCollection<string> p)
+ {
+ if (step != Step.Settings) return;
+ if (p.Contains("full")) scope = ShareScope.Full;
+ if (p.Contains("pw")) usePassword = true;
+ if (p.Contains("names")) names = true;
+ if (p.Contains("30")) days = 30;
+ if (p.Contains("365")) days = 365;
+ Render();
+ if (p.Contains("go")) Go();
+ }
+
+ /// Debug: the blocked step's 去掉这些内容后分享.
+ public void DebugLeaveOut() { if (step == Step.Blocked && LeftAfterRemoving()) LeaveOut(); }
+
+ public string StepName => step.ToString().ToLowerInvariant();
+
+ async void Go()
+ {
+ step = Step.Working;
+ Render();
+ var o = new ShareOptions
+ {
+ Scope = scope, Days = days, Names = names, Password = usePassword ? password.Trim() : null,
+ SummaryInPreview = !usePassword && summaryInPreview, Removed = [.. removed], DropNotes = dropNotes,
+ };
+ switch (await app.Sharing.Share(session, o))
+ {
+ case ShareOutcome.Shared s:
+ record = s.Record;
+ Copy(s.Record.Url, "link");
+ views = 0;
+ step = Step.Done;
+ break;
+ case ShareOutcome.Blocked b:
+ hits = b.Hits; kept = b.Kept;
+ step = Step.Blocked;
+ break;
+ case ShareOutcome.Failed f:
+ failure = Message(f.Code);
+ step = Step.Failed;
+ break;
+ }
+ if (IsLoaded) Render();
+ }
+
+ UIElement Working()
+ {
+ var p = new StackPanel();
+ p.Children.Add(Header(L("分享这场会议")));
+ var bar = new ProgressBar { IsIndeterminate = true, Height = 6, Width = 120, Foreground = Palette.Ink, Background = Palette.Subtle, BorderThickness = new Thickness(0) };
+ var row = Ui.Row(10, bar, Ui.Text(L("正在检查有没有敏感内容…"), 13, Palette.Secondary));
+ row.HorizontalAlignment = HorizontalAlignment.Center;
+ p.Children.Add(new Border { MinHeight = 96, Child = row, Padding = new Thickness(0, 36, 0, 36) });
+ return p;
+ }
+
+ // MARK: Blocked
+
+ UIElement BlockedView()
+ {
+ var p = new StackPanel();
+ p.Children.Add(Ui.Row(8, Ui.Icon(Icons.Warning, 18, Palette.AccentText), Ui.Text(L("检测到潜在敏感内容"), 20, Palette.Ink, FontWeights.Bold)));
+ p.Children.Add(Gap(Ui.Text(L("链接尚未生成。请先核对以下内容:"), 12, Palette.Secondary), 8));
+ foreach (var h in hits.Take(5)) p.Children.Add(Gap(HitRow(h), 8));
+ if (hits.Count > 5) p.Children.Add(Gap(Ui.Text(LF("还有 %lld 处", hits.Count - 5), 12, Palette.Secondary), 8));
+ var leftover = LeftAfterRemoving();
+ p.Children.Add(Gap(Ui.Helper(leftover ? L("去掉后再检查一次;你的记录不会改动。") : L("去掉这些内容后就没有可分享的了。")), 14));
+ var back = Ui.Button(L("返回修改"), () => { step = Step.Settings; Render(); });
+ if (leftover)
+ {
+ var go = Ui.Button(L("去掉这些内容后分享"), LeaveOut, Ui.Kind.Primary);
+ go.IsDefault = true;
+ p.Children.Add(Gap(Buttons(back, go), 24));
+ }
+ else p.Children.Add(Gap(Buttons(back), 24));
+ return p;
+ }
+
+ void LeaveOut()
+ {
+ removed.UnionWith(ShareHit.RecordLines(hits, kept));
+ if (hits.Any(h => h.Part == "notes")) dropNotes = true;
+ Go();
+ }
+
+ /// Would anything be left to share once the flagged parts are out? (A notes-only share whose
+ /// notes were flagged has nothing; the server would refuse an empty document.)
+ bool LeftAfterRemoving()
+ {
+ var notesLeft = HasNotes && !dropNotes && !hits.Any(h => h.Part == "notes");
+ if (scope != ShareScope.Full) return notesLeft;
+ var gone = new HashSet<int>(removed);
+ gone.UnionWith(ShareHit.RecordLines(hits, kept));
+ return notesLeft || Enumerable.Range(0, session.Lines.Count).Any(i => !gone.Contains(i) && session.Lines[i].Src.Length > 0);
+ }
+
+ FrameworkElement HitRow(ShareHit h)
+ {
+ var what = string.Join("、", h.Questions.Select(Category));
+ string place, quote;
+ if (h.Part == "notes")
+ {
+ place = L("纪要");
+ quote = session.Notes?.Summary ?? "";
+ }
+ else
+ {
+ var lines = ShareHit.RecordLines([h], kept).Order().ToList();
+ var a = lines.Count > 0 ? Languages.Clock(session.Lines[lines[0]].T) : "";
+ var b = lines.Count > 0 ? Languages.Clock(session.Lines[lines[^1]].T) : "";
+ place = a == b ? a : $"{a}–{b}";
+ quote = lines.Count > 0 ? session.Lines[lines[0]].Src : "";
+ }
+ var q = Ui.Text(quote, 12, Palette.Secondary);
+ q.MaxHeight = 36; q.TextTrimming = TextTrimming.CharacterEllipsis;
+ return new Border
+ {
+ Background = Palette.AccentPale, CornerRadius = new CornerRadius(8), Padding = new Thickness(10),
+ Child = new StackPanel { Children = { Ui.Text($"{what} · {place}", 12, Palette.Ink, FontWeights.SemiBold), Gap(q, 3) } },
+ };
+ }
+
+ static string Category(string q) => q switch
+ {
+ "credential" => L("密码或密钥"),
+ "confidential" => L("未公开的公司信息"),
+ "crossborder" => L("不宜跨境传输的信息"),
+ "personal" => L("个人身份信息"),
+ "harmful" => L("违法或危险内容"),
+ _ => q,
+ };
+
+ // MARK: Done
+
+ UIElement DoneView(ShareRecord r)
+ {
+ var p = new StackPanel();
+ p.Children.Add(Header(copied == "link" ? L("链接已复制") : L("已分享")));
+ p.Children.Add(Gap(Copyable(r.Url, "link", L("复制链接")), 16));
+ if (r.Password is { } pw) p.Children.Add(Gap(Copyable(pw, "password", L("复制密码")), 8));
+ p.Children.Add(Gap(Ui.Text(Status(r), 12, Palette.Secondary), 12));
+ p.Children.Add(Gap(new Border { Height = 1, Background = Palette.Line }, 16));
+ if (confirmRevoke)
+ {
+ p.Children.Add(Gap(Ui.Text(L("取消后链接立即失效"), 13, Palette.Ink, FontWeights.SemiBold), 16));
+ p.Children.Add(Gap(Ui.Helper(L("已查看过的人可能留有副本。")), 4));
+ Button? stop = null;
+ stop = Ui.Button(L("取消分享"), async () =>
+ {
+ stop!.IsEnabled = false;
+ if (await app.Sharing.Revoke(r, session.Id)) { Log.Debug("share: revoked from the dialog"); Close(); }
+ else { failure = Message("network"); step = Step.Failed; Render(); }
+ }, Ui.Kind.Danger);
+ p.Children.Add(Gap(Buttons(Ui.Button(L("暂不取消"), () => { confirmRevoke = false; Render(); }), stop), 12));
+ }
+ else
+ {
+ var done = Ui.Button(L("完成"), Close, Ui.Kind.Primary);
+ done.IsDefault = true;
+ var row = new Grid();
+ row.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });
+ row.ColumnDefinitions.Add(new ColumnDefinition());
+ row.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });
+ row.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto });
+ var stop = Ui.Button(L("取消分享"), () => { confirmRevoke = true; Render(); }, Ui.Kind.Subtle);
+ var open = Ui.Button(L("在浏览器中打开"), () => Controller.Open(r.Url));
+ open.Margin = new Thickness(0, 0, 8, 0);
+ Grid.SetColumn(open, 2); Grid.SetColumn(done, 3);
+ row.Children.Add(stop); row.Children.Add(open); row.Children.Add(done);
+ p.Children.Add(Gap(row, 16));
+ }
+ return p;
+ }
+
+ FrameworkElement Copyable(string text, string what, string label)
+ {
+ var value = new TextBox
+ {
+ Text = text, IsReadOnly = true, BorderThickness = new Thickness(0), Background = Brushes.Transparent, FontSize = 12,
+ FontFamily = new FontFamily("Cascadia Mono, Consolas"), Foreground = Palette.Ink, VerticalAlignment = VerticalAlignment.Center,
+ };
+ var box = new Border { Background = Palette.Subtle, CornerRadius = new CornerRadius(6), Padding = new Thickness(6, 0, 8, 0), Child = value, Height = 32, VerticalAlignment = VerticalAlignment.Center };
+ var b = Ui.Button(copied == what ? L("已复制") : label, () => { Copy(text, what); Render(); }, height: 32);
+ b.MinWidth = 0; b.Margin = new Thickness(8, 0, 0, 0);
+ var d = new DockPanel();
+ DockPanel.SetDock(b, Dock.Right);
+ d.Children.Add(b); d.Children.Add(box);
+ return d;
+ }
+
+ string Status(ShareRecord r)
+ {
+ var left = Math.Max(1, (int)Math.Ceiling((r.ExpiresAt - DateTimeOffset.Now).TotalDays));
+ var expiry = LF("%lld 天后失效", left);
+ return views is { } v ? expiry + " · " + LF("打开 %lld 次", v) : expiry;
+ }
+
+ async void LoadViews(ShareRecord r)
+ {
+ var stats = await app.Sharing.StatsOf([r.Id]);
+ if (!stats.TryGetValue(r.Id, out var s)) return;
+ if (s.State != "live") { app.Sharing.Store.Remove(session.Id); record = null; step = Step.Settings; }
+ else views = s.Views;
+ if (IsLoaded || step == Step.Settings) Render();
+ }
+
+ void Copy(string text, string what)
+ {
+ try { Clipboard.SetText(text); copied = what; }
+ catch (Exception e) { Log.Debug($"share: copy failed {e.GetType().Name}"); }
+ }
+
+ // MARK: Failed
+
+ UIElement FailedView()
+ {
+ var p = new StackPanel();
+ p.Children.Add(Header(L("没有分享出去")));
+ p.Children.Add(Gap(Ui.Text(failure ?? "", 14, Palette.Body), 12));
+ var retry = Ui.Button(L("重试"), Go, Ui.Kind.Primary);
+ retry.IsDefault = true;
+ p.Children.Add(Gap(Buttons(Ui.Button(L("关闭"), Close), retry), 24));
+ return p;
+ }
+
+ static string Message(string code) => code switch
+ {
+ "rate_limited" or "too_many_shares" => L("分享得太频繁了,请稍后再试。"),
+ "review_unavailable" => L("敏感内容检查暂时不可用,没有检查就不会分享。请稍后再试。"),
+ "sharing_off" => L("分享功能暂时关闭了。"),
+ "update_required" => L("请先更新知了。"),
+ "too_large" => L("这场会议太长,可以只分享纪要。"),
+ "bad_document" => L("这场会议没有可分享的内容。"),
+ "network" => L("连不上 cicada.indaloop.app,请检查网络。"),
+ _ => L("服务器出了问题,请稍后再试。"),
+ };
+
+ // MARK: Parts
+
+ UIElement Header(string title)
+ {
+ var sub = Ui.Text(SessionStore.DisplayTitle(session), 12, Palette.Secondary, wrap: false);
+ return new StackPanel { Children = { Ui.Text(title, 20, Palette.Ink, FontWeights.Bold), Gap(sub, 4) } };
+ }
+
+ static FrameworkElement Row(string title, FrameworkElement control) => Ui.Spread(Ui.Text(title, 14, Palette.Ink), control);
+
+ static RadioButton Radio(string label, bool on, bool enabled, Action chosen)
+ {
+ var r = new RadioButton
+ {
+ Content = Ui.Text(label, 14, enabled ? Palette.Ink : Palette.Tertiary), IsChecked = on, IsEnabled = enabled, GroupName = "share-scope",
+ VerticalContentAlignment = VerticalAlignment.Center, Cursor = Cursors.Hand,
+ };
+ r.Checked += (_, _) => chosen();
+ return r;
+ }
+
+ /// Equal buttons on one row, the last (primary) on the right, as Dialogs.
+ static Grid Buttons(params Button[] buttons)
+ {
+ var g = new Grid();
+ for (int i = 0; i < buttons.Length; i++)
+ {
+ if (i > 0) g.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(8) });
+ g.ColumnDefinitions.Add(new ColumnDefinition());
+ Grid.SetColumn(buttons[i], i * 2);
+ g.Children.Add(buttons[i]);
+ }
+ return g;
+ }
+
+ static T Gap<T>(T e, double top) where T : FrameworkElement { e.Margin = new Thickness(e.Margin.Left, top, e.Margin.Right, e.Margin.Bottom); return e; }
+}
diff --git a/windows/src/Cicada/Ui.cs b/windows/src/Cicada/Ui.cs
index f2eee83..fe31655 100644
--- a/windows/src/Cicada/Ui.cs
+++ b/windows/src/Cicada/Ui.cs
@@ -89,6 +89,7 @@ static class Icons
public const string Chevron = "M6,8 L10,12 L14,8";
public const string Check = "M4.5,10.5 L8,14 L15.5,6";
public const string Info = "M17,10 A7,7 0 1 1 3,10 A7,7 0 1 1 17,10 Z M10,9 V14 M10,6.5 V7";
+ public const string Warning = "M10,3 L17.5,16 H2.5 Z M10,8 V11.5 M10,13.8 V14";
public const string Mic = "M10,2.5 A2.5,2.5 0 0 1 12.5,5 V10 A2.5,2.5 0 0 1 7.5,10 V5 A2.5,2.5 0 0 1 10,2.5 Z M5,9.5 A5,5 0 0 0 15,9.5 M10,14.5 V17.5";
public const string Lock = "M5.5,9 H14.5 V16.5 H5.5 Z M7.5,9 V6.5 A2.5,2.5 0 0 1 12.5,6.5 V9";
public const string Arrow = "M4,10 H15.5 M11,5.5 L15.5,10 L11,14.5";
diff --git a/windows/tests/Cicada.Tests/Cicada.Tests.csproj b/windows/tests/Cicada.Tests/Cicada.Tests.csproj
index 67770ae..8825ad8 100644
--- a/windows/tests/Cicada.Tests/Cicada.Tests.csproj
+++ b/windows/tests/Cicada.Tests/Cicada.Tests.csproj
@@ -9,6 +9,8 @@
<None Include="../../../Resources/**/Localizable.strings*" LinkBase="Resources" CopyToOutputDirectory="PreserveNewest" />
<None Include="../../src/Cicada/Strings/**/Windows.strings" LinkBase="Resources" CopyToOutputDirectory="PreserveNewest" />
<None Include="Fixtures/**" CopyToOutputDirectory="PreserveNewest" />
+ <!-- The share document contract, shared with the Mac and the server (Tests/fixtures/share). -->
+ <None Include="../../../Tests/fixtures/share/**" LinkBase="Fixtures/share" CopyToOutputDirectory="PreserveNewest" />
<ProjectReference Include="../../src/Cicada.Core/Cicada.Core.csproj" />
</ItemGroup>
</Project>
diff --git a/windows/tests/Cicada.Tests/Program.cs b/windows/tests/Cicada.Tests/Program.cs
index 0e5c1de..01de17a 100644
--- a/windows/tests/Cicada.Tests/Program.cs
+++ b/windows/tests/Cicada.Tests/Program.cs
@@ -3,6 +3,7 @@
// LingClient runs against a fake handler.
using System.Net;
using System.Reflection;
+using System.Text;
using System.Text.Json.Nodes;
using System.Text.RegularExpressions;
using Cicada;
@@ -3161,4 +3162,180 @@ static class Tests
}
finally { LingClient.Spacing = old; }
}
+
+ // MARK: 分享… (the Mac's ShareTests, case for case: Tests/fixtures/share is the contract)
+
+ static Session ShareSession() =>
+ Json.Read<Session>(File.ReadAllText(Path.Combine(AppContext.BaseDirectory, "Fixtures", "share", "session.json")))!;
+
+ public static void ShareFixtureBytes()
+ {
+ var want = File.ReadAllText(Path.Combine(AppContext.BaseDirectory, "Fixtures", "share", "share-doc.json")).Trim();
+ Equal(want, ShareProjection.Encode(ShareProjection.Doc(ShareSession(), ShareScope.Full, names: false)), "the Mac's bytes");
+ }
+
+ public static void ShareNothingPrivateLeaves()
+ {
+ var text = ShareProjection.Encode(ShareProjection.Doc(ShareSession(), ShareScope.Full, names: false));
+ foreach (var secret in new[] { "/Users/someone", "Emma", "Kenji", "Emmer", "Sure, Emma", "hasAudio", "room", "voice" })
+ Check(!text.Contains(secret), secret);
+ }
+
+ public static void ShareNamesWhenAsked()
+ {
+ var d = ShareProjection.Doc(ShareSession(), ShareScope.Full, names: true);
+ Equal("Emma", d.Notes!.Todos[0].Owner, "todo owner");
+ Equal("Emma", d.Notes!.Terms[0].Name, "term");
+ Equal(null, d.Notes!.Conclusions[0].Owner, "conclusions never have one");
+ }
+
+ public static void ShareNotesOnlyAndRemoved()
+ {
+ var s = ShareSession();
+ Equal(0, ShareProjection.Doc(s, ShareScope.Notes, false).Lines.Count, "notes only");
+ var d = ShareProjection.Doc(s, ShareScope.Full, false, new HashSet<int> { 3 }, dropNotes: true);
+ Check(d.Lines.Count == 3 && d.Notes is null && d.Hidden == 2, "removed lines and notes counted");
+ Check(!ShareProjection.Encode(d).Contains("\"notes\""), "no notes key");
+ }
+
+ public static void ShareSpeakerNumbersWithoutNames()
+ {
+ var s = ShareSession();
+ s.Lines = [.. Enumerable.Range(0, 10).Select(i => new TranscriptLine
+ {
+ Id = $"v{i}", T = i, Speaker = "them", Src = $"this is line number {i}", Dst = $"第 {i} 句话", SrcLang = "en", DstLang = "zh", Voice = i % 2 == 0 ? 3 : 7,
+ })];
+ Equal("说话人 1,说话人 2", string.Join(",", ShareProjection.Doc(s, ShareScope.Full, false).Lines.Select(l => l.Who).Distinct().Order()), "numbers");
+ Equal("Emma,Kenji", string.Join(",", ShareProjection.Doc(s, ShareScope.Full, true).Lines.Select(l => l.Who).Distinct().Order()), "names");
+ }
+
+ public static void ShareRoundsAndLanguages()
+ {
+ var s = ShareSession();
+ s.Lines = [
+ new TranscriptLine { Id = "a", T = 0.25, Src = "x", Dst = "x", SrcLang = "ja-JP", DstLang = "zh-Hans" },
+ new TranscriptLine { Id = "b", T = 0.35, Src = "y", Dst = "", SrcLang = "en-US", DstLang = "zh" },
+ new TranscriptLine { Id = "c", T = 1.05, Src = "z", Dst = "zz", SrcLang = "en", DstLang = "zh-CN" },
+ ];
+ var d = ShareProjection.Doc(s, ShareScope.Full, false);
+ Equal("0.3,0.4,1.1", string.Join(",", d.Lines.Select(l => l.T.ToString(System.Globalization.CultureInfo.InvariantCulture))), "half away from zero");
+ Check(d.Lines[0].Dst is null && d.Lines[1].Dst is null, "dst left out when empty or the same");
+ Equal("en,zh", string.Join(",", d.Langs), "most lines by base code");
+ Equal("\"a\\\"b\\\\c\\nd/e\"", ShareProjection.Encode(d with { Title = "a\"b\\c\nd/e" }).Split("\"title\":")[^1].Split(",\"v\"")[0], "escapes as Swift");
+ }
+
+ public static void SharePasswordVerifier()
+ {
+ var salt = Enumerable.Repeat((byte)1, 16).ToArray();
+ var v = SharePassword.Verifier("ruby-41-lake", salt, 1000);
+ Equal("eab69fcd00a0517794c156495dd76ad1fbfb036ea03df3d59a68a33519009c81", Convert.ToHexStringLower(v), "the browser's PBKDF2");
+ Check(!v.SequenceEqual(SharePassword.Verifier("ruby-41-laka", salt, 1000)), "another password");
+ Equal(3, SharePassword.Make().Split('-').Length, "word-NN-word");
+ }
+
+ public static void ShareBlockedHitsMapBack()
+ {
+ var hits = new[] { new ShareHit("lines", 2, 3, ["credential"]), new ShareHit("notes", null, null, ["personal"]) };
+ Equal("4,5", string.Join(",", ShareHit.RecordLines(hits, [0, 1, 4, 5, 6]).Order()), "sent lines back to the record's");
+ }
+
+ public static void Ed25519Rfc8032()
+ {
+ (string sk, string pk, string msg, string sig)[] vectors =
+ [
+ ("9d61b19deffd5a60ba844af492ec2cc44449c5697b326919703bac031cae7f60", "d75a980182b10ab7d54bfed3c964073a0ee172f3daa62325af021a68f707511a", "",
+ "e5564300c360ac729086e2cc806e828a84877f1eb8e5d974d873e065224901555fb8821590a33bacc61e39701cf9b46bd25bf5f0595bbe24655141438e7a100b"),
+ ("4ccd089b28ff96da9db6c346ec114e0f5b8a319f35aba624da8cf6ed4fb8a6fb", "3d4017c3e843895a92b70aa74d1b7ebc9c982ccf2ec4968cc0cd55f12af4660c", "72",
+ "92a009a9f0d4cab8720e820b5f642540a2b27b5416503f8fb3762223ebdb69da085ac1e43e15996e458f3613d0f11d8c387b2eaeb4302aeeb00d291612bb0c00"),
+ ("c5aa8df43f9f837bedb7442f31dcb7b166d38535076f094b85ce3a2e0b4458f7", "fc51cd8e6218a1a38da47ed00230f0580816ed13ba3303ac5deb911548908025", "af82",
+ "6291d657deec24024827e69c3abe01a30ce548a284743a445e3680d7db5ac3ac18ff9b538d16f290ae67f760984dc6594a7c15e9716ed28dc027beceea1ec40a"),
+ ];
+ foreach (var (sk, pk, msg, sig) in vectors)
+ {
+ var seed = Convert.FromHexString(sk);
+ var m = Convert.FromHexString(msg);
+ Equal(pk, Convert.ToHexStringLower(Ed25519.PublicKey(seed)), "public key");
+ Equal(sig, Convert.ToHexStringLower(Ed25519.Sign(seed, m)), "signature");
+ Check(Ed25519.Verify(Convert.FromHexString(pk), m, Convert.FromHexString(sig)), "verifies");
+ var bad = Convert.FromHexString(sig); bad[5] ^= 1;
+ Check(!Ed25519.Verify(Convert.FromHexString(pk), m, bad), "a changed signature doesn't");
+ }
+ }
+
+ static byte[] UnB64Url(string s) => Convert.FromBase64String(s.Replace('-', '+').Replace('_', '/').PadRight((s.Length + 3) / 4 * 4, '='));
+
+ /// Answers the share service's routes and checks each signed request as server/src/auth.js does.
+ sealed class ShareServer(Func<HttpRequestMessage, string, HttpResponseMessage> respond) : HttpMessageHandler
+ {
+ public readonly List<string> Seen = [];
+ public byte[]? Pub;
+ protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage r, CancellationToken cancel)
+ {
+ var body = r.Content is null ? "" : await r.Content.ReadAsStringAsync(cancel);
+ var path = r.RequestUri!.PathAndQuery;
+ if (path == "/api/v1/devices")
+ {
+ var j = JsonNode.Parse(body)!;
+ Pub = UnB64Url(j["key"]!.GetValue<string>());
+ var h = System.Security.Cryptography.SHA256.HashData([.. Pub, .. UnB64Url(j["pow"]!.GetValue<string>())]);
+ Check(h[0] == 0 && h[1] == 0 && h[2] < 16, "proof of work");
+ Check(j["platform"]!.GetValue<string>() == "windows", "platform");
+ }
+ else
+ {
+ string H(string k) => r.Headers.TryGetValues("X-Cicada-" + k, out var v) ? v.First() : "";
+ var message = $"{r.Method.Method}\n{path}\n{H("Time")}\n{H("Nonce")}\n{Convert.ToHexStringLower(System.Security.Cryptography.SHA256.HashData(Encoding.UTF8.GetBytes(body)))}";
+ Check(Ed25519.Verify(Pub!, Encoding.UTF8.GetBytes(message), UnB64Url(H("Signature"))), "signed " + path);
+ Check(Regex.IsMatch(H("Nonce"), "^[A-Za-z0-9_-]{16,64}$"), "nonce");
+ }
+ Check(r.Headers.GetValues("X-Cicada-Client").First() == "windows/9.9.9", "client header");
+ lock (Seen) Seen.Add($"{r.Method.Method} {path}");
+ return respond(r, body);
+ }
+ }
+
+ public static async Task ShareClientSignsAndStores()
+ {
+ var folder = Path.Combine(Paths.Root, "share-test");
+ bool forgotten = true;
+ var server = new ShareServer((r, body) =>
+ {
+ var path = r.RequestUri!.AbsolutePath;
+ if (path == "/api/v1/devices") return Status(201, "{\"device\":\"0123456789abcdef0123456789abcdef\"}");
+ if (path == "/api/v1/shares" && r.Method == HttpMethod.Post)
+ {
+ // The first signed call finds the device forgotten: the client registers again once.
+ if (forgotten) { forgotten = false; return Status(401, "{\"code\":\"unknown_device\"}"); }
+ var j = JsonNode.Parse(body)!;
+ Check(r.Headers.GetValues("Idempotency-Key").First().StartsWith("20261106-140000-"), "idempotency key");
+ if (j["scope"]!.GetValue<string>() == "full")
+ return Status(422, "{\"code\":\"blocked\",\"hits\":[{\"part\":\"lines\",\"from\":1,\"to\":1,\"questions\":[\"credential\"]}]}");
+ Check(j["password"]!["iter"]!.GetValue<int>() == 210000, "iterations");
+ Check(j["doc"]!["lines"]!.AsArray().Count == 0 && j["doc"]!["notes"] is not null, "notes only");
+ return Status(201, "{\"id\":\"AAAAAAAAAAAAAAAAAAAAAA\",\"url\":\"https://x/s/AAAAAAAAAAAAAAAAAAAAAA\",\"token\":\"tok\",\"expiresAt\":1900000000}");
+ }
+ if (r.Method == HttpMethod.Get) return Status(200, "{\"shares\":[{\"id\":\"AAAAAAAAAAAAAAAAAAAAAA\",\"expiresAt\":1900000000,\"state\":\"live\",\"views\":3}]}");
+ if (r.Method == HttpMethod.Delete)
+ {
+ Check(r.Headers.Authorization?.ToString() == "Bearer tok", "manage token");
+ return new HttpResponseMessage(HttpStatusCode.NoContent);
+ }
+ return Status(404, "{\"code\":\"not_found\"}");
+ });
+ var client = new ShareClient(new PlainProtector(), "windows", "9.9.9", server, folder);
+ var s = ShareSession();
+ var shared = await client.Share(s, new ShareOptions { Password = "ruby-41-lake" }) as ShareOutcome.Shared;
+ Check(shared is not null, "shared");
+ Equal(2, server.Seen.Count(x => x == "POST /api/v1/devices"), "registered again after unknown_device");
+ Equal("tok", client.Store.Read(s.Id)!.Token, "token kept");
+ Equal("ruby-41-lake", client.Store.Read(s.Id)!.Password, "password kept");
+ if (!OperatingSystem.IsWindows())
+ Equal(UnixFileMode.UserRead | UnixFileMode.UserWrite, File.GetUnixFileMode(Path.Combine(folder, "Shares", s.Id + ".json")), "0600");
+ Equal(3, (await client.StatsOf(["AAAAAAAAAAAAAAAAAAAAAA"]))["AAAAAAAAAAAAAAAAAAAAAA"].Views, "views");
+ var blocked = await client.Share(s, new ShareOptions { Scope = ShareScope.Full }) as ShareOutcome.Blocked;
+ Equal("1", string.Join(",", ShareHit.RecordLines(blocked!.Hits, blocked.Kept)), "blocked line");
+ Check(await client.Revoke(shared!.Record, s.Id), "revoked");
+ Equal(null, client.Store.Read(s.Id), "forgotten after revoke");
+ Equal(2, server.Seen.Count(x => x == "POST /api/v1/devices"), "the device file is reused");
+ }
}