Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
using System.Globalization;
using System.Net;

namespace OpenCode.Sdk.Internal;

/// <summary>The CLI's exact HTTP(S) origin and ECMAScript item-trimming policy.</summary>
internal static class CorsOriginPolicy
{
private static readonly char[] TrimCharacters =
['\u0009', '\u000a', '\u000b', '\u000c', '\u000d', '\u0020', '\u00a0', '\u1680',
'\u2000', '\u2001', '\u2002', '\u2003', '\u2004', '\u2005', '\u2006', '\u2007', '\u2008', '\u2009', '\u200a',
'\u2028', '\u2029', '\u202f', '\u205f', '\u3000', '\ufeff'];

/// <summary>Trims exactly JavaScript WhiteSpace and LineTerminator code points.</summary>
/// <param name="value">One comma-list item.</param>
/// <returns>The trimmed item.</returns>
public static string TrimItem(string value) => value.Trim(TrimCharacters);

/// <summary>Tests whether the item equals its canonical HTTP(S) URL origin.</summary>
/// <param name="origin">The already-trimmed item.</param>
/// <returns>Whether the CLI accepts it unchanged as an origin.</returns>
public static bool IsOrigin(string origin)
{
if (!Uri.TryCreate(origin, UriKind.Absolute, out var uri) || uri.Scheme is not ("http" or "https"))
{
return false;
}

var host = uri.IdnHost.ToLowerInvariant();
if (uri.HostNameType == UriHostNameType.IPv6)
{
if (host.Contains('%', StringComparison.Ordinal) || !IPAddress.TryParse(host, out var address))
{
return false;
}

host = "[" + SerializeIpv6(address) + "]";
}
else if (uri.HostNameType != UriHostNameType.IPv4 && !IsDomain(host))
{
return false;
}

var canonical = uri.Scheme + "://" + host
+ (uri.IsDefaultPort ? string.Empty : ":" + uri.Port.ToString(CultureInfo.InvariantCulture));
return string.Equals(origin, canonical, StringComparison.Ordinal);
}

private static bool IsDomain(string host)
{
var labels = host.TrimEnd('.').Split('.');
var last = labels[^1];
// A numeric final label invokes WHATWG's IPv4 parser, not DNS, even when Uri accepts DNS.
if (last.All(static character => character is >= '0' and <= '9')
|| (last.StartsWith("0x", StringComparison.Ordinal) && last.Skip(2).All(Uri.IsHexDigit)))
{
return false;
}

try
{
var idn = new IdnMapping();
return labels.Where(static label => label.StartsWith("xn--", StringComparison.Ordinal))
.All(label => string.Equals(idn.GetAscii(idn.GetUnicode(label)), label, StringComparison.Ordinal));
}
catch (ArgumentException)
{
return false;
}
}

private static string SerializeIpv6(IPAddress address)
{
var bytes = address.GetAddressBytes();
var groups = Enumerable.Range(0, 8).Select(index => (bytes[index * 2] << 8) | bytes[(index * 2) + 1]).ToArray();
var start = -1;
var length = 1;
for (var index = 0; index < groups.Length; index++)
{
var end = index;
while (end < groups.Length && groups[end] == 0)
{
end++;
}

if (end - index > length)
{
start = index;
length = end - index;
}
}

var text = groups.Select(static group => group.ToString("x", CultureInfo.InvariantCulture)).ToArray();
return start < 0 ? string.Join(':', text)
: string.Join(':', text.Take(start)) + "::" + string.Join(':', text.Skip(start + length));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,26 @@ internal sealed class ServiceConfigDocument
/// <param name="remoteRoute">The current remote route, or null when unset.</param>
/// <param name="legacyRemote">The earlier boolean remote setting, or null for the current shape.</param>
/// <param name="password">The stored password, or null when unset.</param>
internal ServiceConfigDocument(string? remoteRoute = null, bool? legacyRemote = null, string? password = null)
/// <param name="disabled">The saved disabled flag.</param>
/// <param name="remoteAccepted">The saved acceptance marker.</param>
/// <param name="hostname">The saved hostname.</param>
/// <param name="port">The saved port.</param>
/// <param name="corsOrigins">The saved origins.</param>
/// <param name="environment">The saved environment entries.</param>
internal ServiceConfigDocument(
bool? disabled = null, string? remoteRoute = null, bool? legacyRemote = null, bool? remoteAccepted = null,
string? hostname = null, int? port = null, string? password = null,
IReadOnlyList<string>? corsOrigins = null, IReadOnlyDictionary<string, string>? environment = null)
{
Disabled = disabled;
RemoteRoute = remoteRoute;
LegacyRemote = legacyRemote;
RemoteAccepted = remoteAccepted;
Hostname = hostname;
Port = port;
Password = password;
CorsOrigins = corsOrigins;
Environment = environment;
}

/// <summary>Gets present members in the decode's schema order, or the subsequent merge's order.</summary>
Expand All @@ -27,15 +42,92 @@ internal ServiceConfigDocument(string? remoteRoute = null, bool? legacyRemote =

/// <summary>Assigns without moving an existing password, adding an absent one last.</summary>
/// <param name="password">The credential to persist.</param>
public void AssignPassword(string password)
public void AssignPassword(string? password)
{
var members = Members;
if (Password is null)
SetPresence("password", password is not null);
Password = password;
}

/// <summary>Assigns the hostname without moving an existing member.</summary>
/// <param name="hostname">The value, including an empty string.</param>
public void AssignHostname(string? hostname)
{
SetPresence("hostname", hostname is not null);
Hostname = hostname;
}

/// <summary>Assigns or drops the disabled preference without moving it.</summary>
public void AssignDisabled(bool? disabled)
{
SetPresence("disabled", disabled is not null);
Disabled = disabled;
}

/// <summary>Assigns acceptance without moving an existing marker.</summary>
public void AssignRemoteAccepted(bool accepted)
{
SetPresence("remoteAccepted", accepted);
RemoteAccepted = accepted ? true : null;
}

/// <summary>Assigns or drops the port without moving it.</summary>
public void AssignPort(int? port)
{
SetPresence("port", port is not null);
Port = port;
}

/// <summary>Assigns or drops origins without moving an existing member.</summary>
public void AssignCorsOrigins(IReadOnlyList<string>? origins)
{
SetPresence("cors", origins is not null);
CorsOrigins = origins;
}

/// <summary>Assigns or drops environment entries without moving an existing member.</summary>
public void AssignEnvironment(IReadOnlyDictionary<string, string>? environment)
{
SetPresence("env", environment is not null);
Environment = environment;
}

/// <summary>Removes a setting and its value; remote and environment have dedicated operations.</summary>
public void RemoveSetting(OpenCodeServiceSetting setting)
{
switch (setting)
{
members.Add("password");
case OpenCodeServiceSetting.Disabled:
AssignDisabled(null);
break;
case OpenCodeServiceSetting.Hostname:
AssignHostname(null);
break;
case OpenCodeServiceSetting.Port:
AssignPort(null);
break;
case OpenCodeServiceSetting.Password:
AssignPassword(null);
break;
case OpenCodeServiceSetting.CorsOrigins:
AssignCorsOrigins(null);
break;
}
}

Password = password;
/// <summary>Removes env before an unset appends any remaining entries last.</summary>
public void RemoveEnvironment() => AssignEnvironment(null);

private void SetPresence(string member, bool present)
{
var members = Members;
if (!present)
{
_ = members.Remove(member);
}
else if (!members.Contains(member, StringComparer.Ordinal))
{
members.Add(member);
}
}

/// <summary>Drops a legacy boolean, adding a generated remote object last only when enabled.</summary>
Expand Down Expand Up @@ -66,7 +158,7 @@ public void RepairRemote(string? route)
};

/// <summary>Gets the saved connection-mode preference, or null when unset.</summary>
public bool? Disabled { get; init; }
public bool? Disabled { get; private set; }

/// <summary>Gets the current remote route, retained only inside the SDK.</summary>
public string? RemoteRoute { get; private set; }
Expand All @@ -75,20 +167,20 @@ public void RepairRemote(string? route)
public bool? LegacyRemote { get; private set; }

/// <summary>Gets the acceptance marker, true when present and null otherwise.</summary>
public bool? RemoteAccepted { get; init; }
public bool? RemoteAccepted { get; private set; }

/// <summary>Gets the saved hostname, or null when unset.</summary>
public string? Hostname { get; init; }
public string? Hostname { get; private set; }

/// <summary>Gets the saved port, or null when unset.</summary>
public int? Port { get; init; }
public int? Port { get; private set; }

/// <summary>Gets the stored password, retained only inside the SDK.</summary>
public string? Password { get; private set; }

/// <summary>Gets the saved origins in stored order, or null when unset.</summary>
public IReadOnlyList<string>? CorsOrigins { get; init; }
public IReadOnlyList<string>? CorsOrigins { get; private set; }

/// <summary>Gets the saved environment entries, or null when unset.</summary>
public IReadOnlyDictionary<string, string>? Environment { get; init; }
public IReadOnlyDictionary<string, string>? Environment { get; private set; }
}
Original file line number Diff line number Diff line change
@@ -1,8 +1,92 @@
namespace OpenCode.Sdk.Internal;

/// <summary>The non-stopping password edit over the CLI-compatible configuration store.</summary>
internal sealed class ServiceConfigEditor(ServiceConfigStore store)
/// <summary>The CLI's ordered read, stop, re-read and configuration merges.</summary>
internal sealed class ServiceConfigEditor(
ServiceConfigStore store, Func<OpenCodeServerStopOptions, CancellationToken, Task> stop)
{
/// <summary>Changes the saved hostname after stopping the registered service.</summary>
/// <param name="hostname">The guarded value.</param>
/// <param name="selection">The captured selection.</param>
/// <param name="cancellationToken">The caller's token.</param>
/// <returns>The completed write.</returns>
public Task SetHostnameAsync(string hostname, ServiceSelection selection, CancellationToken cancellationToken) =>
ChangeAsync(selection, document => document.AssignHostname(hostname), stopping: true, cancellationToken);

/// <summary>Only enabling the disabled flag stops the service.</summary>
public Task SetDisabledAsync(bool disabled, ServiceSelection selection, CancellationToken cancellationToken) =>
ChangeAsync(selection, document => document.AssignDisabled(disabled), stopping: disabled, cancellationToken);

/// <summary>Stores the validated port after stopping.</summary>
public Task SetPortAsync(int port, ServiceSelection selection, CancellationToken cancellationToken) =>
ChangeAsync(selection, document => document.AssignPort(port), stopping: true, cancellationToken);

/// <summary>Stores the given password, including an empty one, after stopping.</summary>
public Task SetPasswordAsync(string password, ServiceSelection selection, CancellationToken cancellationToken) =>
ChangeAsync(selection, document => document.AssignPassword(password), stopping: true, cancellationToken);

/// <summary>Stores the captured origins in their given order after stopping.</summary>
public Task SetCorsOriginsAsync(IReadOnlyList<string> origins, ServiceSelection selection, CancellationToken cancellationToken) =>
ChangeAsync(selection, document => document.AssignCorsOrigins(origins), stopping: true, cancellationToken);

/// <summary>Updates a present environment name in place, or appends a new name.</summary>
public Task SetEnvironmentVariableAsync(string name, string value, ServiceSelection selection, CancellationToken cancellationToken) =>
ChangeAsync(selection, document =>
{
var environment = (document.Environment ?? Enumerable.Empty<KeyValuePair<string, string>>())
.ToDictionary(static pair => pair.Key, static pair => pair.Value, StringComparer.Ordinal);
environment[name] = value;
document.AssignEnvironment(environment);
}, stopping: true, cancellationToken);

/// <summary>Forgets remote access, recording acceptance only when it was enabled.</summary>
public Task DisableRemoteAsync(ServiceSelection selection, CancellationToken cancellationToken) =>
ChangeAsync(selection, document =>
{
var enabled = document.RemoteRoute is not null;
document.RepairRemote(null);
if (enabled)
{
document.AssignRemoteAccepted(true);
}
}, stopping: true, cancellationToken);

/// <summary>Removes a setting; only the disabled preference is non-stopping.</summary>
public Task UnsetAsync(OpenCodeServiceSetting setting, ServiceSelection selection, CancellationToken cancellationToken) =>
ChangeAsync(selection, document => document.RemoveSetting(setting),
stopping: setting != OpenCodeServiceSetting.Disabled, cancellationToken);

/// <summary>Drops env, then appends its remaining entries last when any survive.</summary>
public Task UnsetEnvironmentVariableAsync(string name, ServiceSelection selection, CancellationToken cancellationToken) =>
ChangeAsync(selection, document =>
{
var remaining = (document.Environment ?? Enumerable.Empty<KeyValuePair<string, string>>())
.Where(pair => !string.Equals(pair.Key, name, StringComparison.Ordinal))
.ToDictionary(static pair => pair.Key, static pair => pair.Value, StringComparer.Ordinal);
document.RemoveEnvironment();
if (remaining.Count != 0)
{
document.AssignEnvironment(remaining);
}
}, stopping: true, cancellationToken);

private async Task ChangeAsync(
ServiceSelection selection, Action<ServiceConfigDocument> merge, bool stopping, CancellationToken cancellationToken)
{
var document = await store.ReadForWriteAsync(selection, cancellationToken).ConfigureAwait(false);
if (stopping)
{
await stop(new OpenCodeServerStopOptions
{
Channel = selection.Channel,
InstalledVersion = selection.InstalledVersion,
}, cancellationToken).ConfigureAwait(false);
document = await store.ReadForWriteAsync(selection, cancellationToken).ConfigureAwait(false);
}

merge(document);
await store.WriteAsync(store.ResolvePaths(selection), document, cancellationToken).ConfigureAwait(false);
}

/// <summary>Returns a stored nonempty password, creating and persisting one otherwise.</summary>
/// <param name="options">The selection, validated before any seam is called.</param>
/// <param name="cancellationToken">The caller's token.</param>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -141,19 +141,17 @@ public static bool IsCurrent(ReadOnlySpan<byte> utf8) =>
_ = StrictJson.TryGetOptionalString(root, "password", out var password);
_ = root.TryGetProperty("remote", out var remote);
return new ServiceConfigDocument(
disabled: root.TryGetProperty("disabled", out var disabled) ? disabled.GetBoolean() : null,
remoteRoute: remote.ValueKind == JsonValueKind.Object ? remote.GetProperty("route").GetString() : null,
legacyRemote: remote.ValueKind is JsonValueKind.True or JsonValueKind.False ? remote.GetBoolean() : null,
password: password)
{
Disabled = root.TryGetProperty("disabled", out var disabled) ? disabled.GetBoolean() : null,
RemoteAccepted = root.TryGetProperty("remoteAccepted", out _) ? true : null,
Hostname = hostname,
Port = root.TryGetProperty("port", out var port) ? (int)port.GetDouble() : null,
remoteAccepted: root.TryGetProperty("remoteAccepted", out _) ? true : null,
hostname: hostname,
port: root.TryGetProperty("port", out var port) ? (int)port.GetDouble() : null,
password: password,
// The shape has proved these strings non-null; GetString also forces strict decoding.
CorsOrigins = root.TryGetProperty("cors", out var cors)
corsOrigins: root.TryGetProperty("cors", out var cors)
? cors.EnumerateArray().Select(static origin => origin.GetString()!).ToArray() : null,
Environment = root.TryGetProperty("env", out _) ? environment : null,
};
environment: root.TryGetProperty("env", out _) ? environment : null);
}

private static Dictionary<string, string>? Read(JsonElement root, bool admitLegacyRemote)
Expand Down
Loading
Loading