Author SHA1 Message Date
terminarandClaude Opus 5.5 5d141c7cef gui/window: native open and save file dialogs
ShowFileDialog (UI thread) and ChooseFile (any goroutine, waits) show a
native dialog for the window -- NSOpenPanel/NSSavePanel as a sheet on
macOS, GetOpenFileNameW/GetSaveFileNameW on Windows -- with a title, a
start folder, a suggested name and allowed extensions. It only returns
the chosen path; one dialog at a time.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 23:41:23 +01:00
terminarandClaude Opus 5.5 e1495430c5 trust: the signing half of publisher signatures
Moved from yet's internal/trust without changing behavior or file
formats: KeyPair, GenerateKey, SaveKeyPair, LoadPrivateKey,
ParsePrivateKey, LoadPublicKey, MarshalPublicKey, SignEd25519,
VerifyEd25519, ExportPEM, ImportPEM, and the package signature as
SignDigest. New: Sign and VerifyMessage, a detached minisign signature
over any bytes and its check (returns the trusted comment; another key
with a colliding ID fails), and KeyFromRef, a key pair from a
core/secretref reference with error messages that never carry the
secret. A golden vector (testdata/sign-vector.*) pins the output, and
VerifySignature is tested against what SignDigest makes.

For yabar's evidence signing (ADR-0037 there, owner decision Q-5
option A); yet keeps registry signing and its auto-sign key store.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 22:08:12 +01:00
terminarandClaude Opus 5.5 9395fadbf7 fix(configcmd): redact secret fields inside list values
"config show" prints a list as one value, and redaction only looked at
the leaf's own key, so the password of every entry of a list (yamocir's
bootstrap.admins) was printed in clear. The same rule now applies inside
lists and maps of a leaf: a field is secret by its default name or by a
Spec.SecretKeys key without the list index ("admins.password").
References (env:, file:, secret://) stay visible as before.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-24 09:47:44 +01:00
terminarandClaude Opus 5.5 8513b6db4c feat(configcmd): Spec.SecretKeys redacts a program's own secret options
"config show" redacted only keys whose last segment is secrets, secret,
token or password. A program's own secrets (database.url,
oidc.client_secret, smtp.url, ...) were printed, so programs disabled
show. Spec.SecretKeys names them as dotted keys (a key covers everything
below it); Effective carries them to Values and Show. First consumer:
yaemp and yaemp-mcp.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 17:32:16 +01:00
terminarandClaude Opus 5.5 31dbc347e8 gui/window: keep the window frame across starts, take the first click
- Options.FrameFile: the window's position, size and maximized state in
  a small JSON file, read at New (a frame on no connected screen is
  ignored, the window opens centered), written shortly after every move
  or resize and at Destroy. macOS: NSWindow frame (the normal frame
  under a zoomed one), checked against NSScreen visible frames; Windows:
  Get/SetWindowPlacement, checked with MonitorFromRect.
- macOS: the web view is a WKWebView subclass that accepts the first
  mouse click, so a page in an inactive window reacts to it instead of
  the click only activating the window (yanks' start dialog).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 15:19:45 +01:00
terminarandClaude Opus 5.5 c16b871db5 TODO: core/gui should accept the first mouse click on macOS
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 13:28:30 +01:00
26 changed files with 1348 additions and 22 deletions

No files matched your search

+5 -2
View File
@@ -374,8 +374,11 @@ report options the program ignores. Taken over from
`config show [--json] [--show-secrets]` prints the configuration with `config show [--json] [--show-secrets]` prints the configuration with
the file every value comes from (`Effective.Show`; secrets -- keys the file every value comes from (`Effective.Show`; secrets -- keys
`secrets`, `secret`, `token`, `password` -- are redacted unless `secrets`, `secret`, `token`, `password`, plus the program's own
`--show-secrets`, references like `env:X` stay visible), and `Spec.SecretKeys` such as `database.url` (a key covers everything below
it) -- are redacted unless `--show-secrets`, references like `env:X`
stay visible; inside a list the same rule applies to every entry's
fields, a Spec key naming them without the index: `admins.password`), and
`configcmd.Doctor(report, spec, explicit)` is the config part of a `configcmd.Doctor(report, spec, explicit)` is the config part of a
`doctor` command (paths, layers, "config file found", unknown options). `doctor` command (paths, layers, "config file found", unknown options).
+7
View File
@@ -47,6 +47,13 @@ speculatively.
`yetano.dev/yetano/core/gui` (`gui/v0.1.0`). The prototype uses it. `yetano.dev/yetano/core/gui` (`gui/v0.1.0`). The prototype uses it.
- [ ] Move yet-gui off its copy in `yet/gui/internal` onto `core/gui` - [ ] Move yet-gui off its copy in `yet/gui/internal` onto `core/gui`
(steps in [gui/README.md](gui/README.md)). (steps in [gui/README.md](gui/README.md)).
- [x] `core/gui` (macOS): the web view accepts the first mouse click in
an inactive window (`YTWebView`, `acceptsFirstMouse:` YES;
`gui/v0.2.0`, 2026-11-15) -- before, the first click only activated
the window, so a dialog shown at start looked dead (yanks).
- [x] `core/gui`: `window.Options.FrameFile` keeps the window's position,
size and maximized state across starts (macOS and Windows;
`gui/v0.2.0`, 2026-11-15).
- [ ] `core/gui`: Linux/FreeBSD backend (WebKitGTK) -- see gui/README.md. - [ ] `core/gui`: Linux/FreeBSD backend (WebKitGTK) -- see gui/README.md.
- [x] `core/tui`: shared TUI kernel (themes, styles, Paint/Outer, - [x] `core/tui`: shared TUI kernel (themes, styles, Paint/Outer,
ListState, text helpers) as the nested module ListState, text helpers) as the nested module
+8
View File
@@ -116,6 +116,14 @@ type Spec struct {
// options (see Missing). Optional. // options (see Missing). Optional.
Schema any Schema any
// SecretKeys are the program's own secret options, as dotted keys
// ("database.url", "oidc.client_secret"): "config show" redacts them
// like the keys it always treats as secret (a last segment secrets,
// secret, token or password). A key also covers everything below it.
// Fields of list entries are named without the index
// ("admins.password" for every entry of the list admins).
SecretKeys []string
// Options are passed through to core/config; tests use them to // Options are passed through to core/config; tests use them to
// inject a platform, environment, root and working directory. // inject a platform, environment, root and working directory.
Options []coreconfig.Option Options []coreconfig.Option
+4
View File
@@ -73,6 +73,9 @@ type Effective struct {
// Loader is the Layered loader's own value for this configuration // Loader is the Layered loader's own value for this configuration
// (e.g. its richer layer list), for its Unknown hook; nil otherwise. // (e.g. its richer layer list), for its Unknown hook; nil otherwise.
Loader any Loader any
// SecretKeys are redacted by Values and Show in addition to the
// default secret names (Spec.SecretKeys).
SecretKeys []string
} }
// Used returns the layers that contributed, highest priority first. // Used returns the layers that contributed, highest priority first.
@@ -233,6 +236,7 @@ func (s Spec) show(explicit string, args []string, stdout, stderr io.Writer) int
return ExitProblem return ExitProblem
} }
used := s.usedFunc() used := s.usedFunc()
e.SecretKeys = s.SecretKeys
if err := e.Show(stdout, used, *asJSON, *secrets); err != nil { if err := e.Show(stdout, used, *asJSON, *secrets); err != nil {
fmt.Fprintf(stderr, "%s config show: %v\n", s.Name, err) fmt.Fprintf(stderr, "%s config show: %v\n", s.Name, err)
return ExitProblem return ExitProblem
+87
View File
@@ -174,6 +174,43 @@ func TestValuesRedaction(t *testing.T) {
} }
} }
// TestValuesProgramSecrets: Spec.SecretKeys (on Effective) redacts a
// program's own secret options and everything below one; other keys and
// a key that only shares a prefix stay.
func TestValuesProgramSecrets(t *testing.T) {
merged, origins := coreconfig.Merge(coreconfig.Source{Name: "f", Data: map[string]any{
"database": map[string]any{"url": "postgres://app:pw@db/x", "owner_url": "file:/run/o", "urls": "kept"},
"smtp": map[string]any{"url": "smtps://u:pw@mail", "from": "a@b"},
"vault": map[string]any{"inner": map[string]any{"key": "deep"}},
}})
e := &Effective{Name: "p", Merged: merged, Origins: origins, SecretKeys: []string{"database.url", "database.owner_url", "smtp.url", "vault"}}
got := map[string]any{}
for _, v := range e.Values(nil, false) {
got[v.Key] = v.Value
}
want := map[string]any{
"database.url": "<redacted>", "database.owner_url": "file:/run/o", "database.urls": "kept",
"smtp.url": "<redacted>", "smtp.from": "a@b", "vault.inner.key": "<redacted>",
}
if !reflect.DeepEqual(got, want) {
t.Errorf("Values = %v, want %v", got, want)
}
for _, v := range e.Values(nil, true) {
if v.Key == "smtp.url" && v.Value != "smtps://u:pw@mail" {
t.Errorf("show-secrets: %v", v.Value)
}
}
// Through "config show": the Spec's keys reach the output.
root := t.TempDir()
s := testSpec(root)
s.SecretKeys = []string{"log-level"}
writeFile(t, filepath.Join(root, "etc", "yamase", "yamase-test.yaml"), minimalTemplate+"log-level: debug\n")
if code, out, errOut := run(t, s, "", "show"); code != ExitOK || strings.Contains(out, `"debug"`) || !strings.Contains(out, `log-level: "<redacted>"`) {
t.Errorf("show: exit %d\n%s%s", code, out, errOut)
}
}
type inlineBase struct { type inlineBase struct {
Enabled bool `yaml:"enabled"` Enabled bool `yaml:"enabled"`
} }
@@ -211,3 +248,53 @@ func statExistsForTest(path string) bool {
_, err := os.Stat(path) _, err := os.Stat(path)
return err == nil return err == nil
} }
// TestValuesRedactionInLists: a list leaf is printed as one value, so
// the secret fields of its entries are redacted inside it -- by default
// name and by a Spec key without the index -- and the rest stays.
func TestValuesRedactionInLists(t *testing.T) {
merged, origins := coreconfig.Merge(coreconfig.Source{Name: "f", Data: map[string]any{
"admins": []any{
map[string]any{"username": "admin", "password": "changeme"},
map[string]any{"username": "ops", "password": "env:OPS_PW", "tags": []any{"a"}},
},
"ids": []any{map[string]any{"name": "gc", "nested": map[string]any{"token": "t0k"}, "url": "pg://u:pw@h"}},
"plain": []any{"x", "y"},
}})
e := &Effective{Name: "p", Merged: merged, Origins: origins, SecretKeys: []string{"ids.url"}}
got := map[string]any{}
for _, v := range e.Values(nil, false) {
got[v.Key] = v.Value
}
want := map[string]any{
"admins": []any{
map[string]any{"username": "admin", "password": "<redacted>"},
map[string]any{"username": "ops", "password": "env:OPS_PW", "tags": []any{"a"}},
},
"ids": []any{map[string]any{"name": "gc", "nested": map[string]any{"token": "<redacted>"}, "url": "<redacted>"}},
"plain": []any{"x", "y"},
}
if !reflect.DeepEqual(got, want) {
t.Errorf("Values = %v\nwant %v", got, want)
}
if merged["admins"].([]any)[0].(map[string]any)["password"] != "changeme" {
t.Error("the merged configuration was changed")
}
for _, v := range e.Values(nil, true) {
if v.Key == "admins" && !strings.Contains(renderValue(v.Value), "changeme") {
t.Errorf("show-secrets: %v", v.Value)
}
}
// Through "config show" from a file, YAML and JSON.
root := t.TempDir()
s := testSpec(root)
writeFile(t, filepath.Join(root, "etc", "yamase", "yamase-test.yaml"),
minimalTemplate+"users:\n - name: a\n password: hunter2\n")
for _, args := range [][]string{{"show"}, {"show", "--json"}} {
code, out, errOut := run(t, s, "", args...)
if code != ExitOK || strings.Contains(out, "hunter2") || !strings.Contains(out, "<redacted>") || !strings.Contains(out, `"name"`) {
t.Errorf("%v: exit %d\n%s%s", args, code, out, errOut)
}
}
}
+50 -4
View File
@@ -28,9 +28,12 @@ const DefaultOrigin = "default"
// Values returns every leaf of e, sorted by key, with its origin. // Values returns every leaf of e, sorted by key, with its origin.
// used reports whether the program reads a key (nil: every key); a // used reports whether the program reads a key (nil: every key); a
// default it does not read is left out. Secret values (keys secrets, // default it does not read is left out. Secret values (keys secrets,
// secret, token, password) are replaced by "<redacted>" unless // secret, token, password, and e.SecretKeys) are replaced by "<redacted>" unless
// showSecrets; a reference that only says where a secret is (env:, // showSecrets; a reference that only says where a secret is (env:,
// file:, secret://) is shown. // file:, secret://) is shown. A leaf that is a list is printed as one
// value, so the same rule is applied inside it: a field of a list entry
// is secret by its name or by its key without the index ("admins.password"
// for the field password of every entry of the list admins).
func (e *Effective) Values(used func(string) bool, showSecrets bool) []Value { func (e *Effective) Values(used func(string) bool, showSecrets bool) []Value {
var out []Value var out []Value
walkLeaves("", e.Merged, func(key string, v any) { walkLeaves("", e.Merged, func(key string, v any) {
@@ -42,8 +45,12 @@ func (e *Effective) Values(used func(string) bool, showSecrets bool) []Value {
if !u && source == DefaultOrigin { if !u && source == DefaultOrigin {
return return
} }
if !showSecrets && isSecretKey(key) { if !showSecrets {
v = redact(v) if e.isSecret(key) {
v = redact(v)
} else {
v = e.redactWithin(key, v)
}
} }
out = append(out, Value{Key: key, Value: v, Source: source, Used: u}) out = append(out, Value{Key: key, Value: v, Source: source, Used: u})
}) })
@@ -117,6 +124,45 @@ var secretKeys = map[string]bool{"secrets": true, "secret": true, "token": true,
func isSecretKey(key string) bool { return secretKeys[key[strings.LastIndex(key, ".")+1:]] } func isSecretKey(key string) bool { return secretKeys[key[strings.LastIndex(key, ".")+1:]] }
// isSecret: a default secret name, or one of e.SecretKeys or a key below
// one.
func (e *Effective) isSecret(key string) bool {
if isSecretKey(key) {
return true
}
for _, k := range e.SecretKeys {
if key == k || strings.HasPrefix(key, k+".") {
return true
}
}
return false
}
// redactWithin redacts the secret fields of the maps inside a list (or
// a map) leaf at key, by the same rule as isSecret. A list entry adds no
// segment to the key. v is copied, never changed.
func (e *Effective) redactWithin(key string, v any) any {
switch x := v.(type) {
case []any:
out := make([]any, len(x))
for i, el := range x {
out[i] = e.redactWithin(key, el)
}
return out
case map[string]any:
out := make(map[string]any, len(x))
for k, el := range x {
if sub := key + "." + k; e.isSecret(sub) {
out[k] = redact(el)
} else {
out[k] = e.redactWithin(sub, el)
}
}
return out
}
return v
}
// redact replaces secret values, keeping references that only say where // redact replaces secret values, keeping references that only say where
// the secret is. // the secret is.
func redact(v any) any { func redact(v any) any {
+9 -1
View File
@@ -38,7 +38,7 @@ the main module's `vX.Y.Z` tags do not version this one. Never move a tag.
| `gui/assets` | `NewResolver(sources...)` over `NewFSSource` (embed.FS), `NewDirSource` (os.Root), `NewZipFileSource`/`NewZipBytesSource`; first source that has a file wins, a read error does not fall through. `ValidatePath` (checked, never cleaned), `Join`, `DetectMIME`. | | `gui/assets` | `NewResolver(sources...)` over `NewFSSource` (embed.FS), `NewDirSource` (os.Root), `NewZipFileSource`/`NewZipBytesSource`; first source that has a file wins, a read error does not fall through. `ValidatePath` (checked, never cleaned), `Join`, `DetectMIME`. |
| `gui/document` | `Prepare(ctx, res, entry, html, Options{Link})`: rewrites `assets:` / relative references in HTML and CSS (`img`, `srcset`, `script`, `link`, `style`, CSS `url()`/`@import`). Link mode -> `/assets/...` URLs, validated against the resolver; inline mode -> typed `data:` URLs (entry <= 1.5 MiB). | | `gui/document` | `Prepare(ctx, res, entry, html, Options{Link})`: rewrites `assets:` / relative references in HTML and CSS (`img`, `srcset`, `script`, `link`, `style`, CSS `url()`/`@import`). Link mode -> `/assets/...` URLs, validated against the resolver; inline mode -> typed `data:` URLs (entry <= 1.5 MiB). |
| `gui/bridge` | `NewRouter(res)`, `Router.Handle("POST /rpc/x", h)`, `Router.SetDocument`, `Router.ServeNative` (for the window's resource handler), `Router.HTML` (Go-rendered fragments through `document`). `NewSession(router, Options)` speaks protocol v1 with the page (`hello`/`ready`, `req`/`res`, `chunk`/`end` streams, `abort`, generations). `InitScript(PageConfig)` is the page side (`bridge.js`). | | `gui/bridge` | `NewRouter(res)`, `Router.Handle("POST /rpc/x", h)`, `Router.SetDocument`, `Router.ServeNative` (for the window's resource handler), `Router.HTML` (Go-rendered fragments through `document`). `NewSession(router, Options)` speaks protocol v1 with the page (`hello`/`ready`, `req`/`res`, `chunk`/`end` streams, `abort`, generations). `InitScript(PageConfig)` is the page side (`bridge.js`). |
| `gui/window` | `New(Options{Title, Width, Height, Debug, DataPath, OnMessage, Resource})`, `Init`, `Navigate`, `Run`, `Dispatch`, `Eval`, `Terminate`, `Destroy`, `BaseURL`, `Snapshot` (macOS), `SetAppearance`, `SetAppIcon`, `AccentColor`. | | `gui/window` | `New(Options{Title, Width, Height, Debug, DataPath, OnMessage, Resource, FrameFile})`, `Init`, `Navigate`, `Run`, `Dispatch`, `Eval`, `Terminate`, `Destroy`, `BaseURL`, `Snapshot` (macOS), `SetAppearance`, `SetAppIcon`, `AccentColor`, `ShowFileDialog` (UI thread) / `ChooseFile` (any goroutine, waits): a native open or save dialog (`FileDialog{Save, Title, Directory, Name, Extensions}`; macOS NSOpenPanel/NSSavePanel as a sheet, Windows GetOpenFileNameW/GetSaveFileNameW), "" when cancelled -- it only returns a path, nothing is read or written. |
## Wiring ## Wiring
@@ -70,6 +70,14 @@ w.Destroy() // then: native window, on the UI thread
The WebView2 user-data folder (`DataPath`) belongs under the program's The WebView2 user-data folder (`DataPath`) belongs under the program's
`core/paths` cache or data directory (`%LOCALAPPDATA%`, never roaming). `core/paths` cache or data directory (`%LOCALAPPDATA%`, never roaming).
`FrameFile` (since `gui/v0.2.0`) keeps the window's position, size and
maximized state across starts: a small JSON file the program places in
its `core/paths` state directory. It is read at `New` -- a frame that is
on no connected screen any more is ignored and the window opens
centered -- and written shortly after every move or resize and at
`Destroy`. The coordinates are the platform's own (macOS: points from
the bottom left; Windows: `WINDOWPLACEMENT`'s normal position).
## Invariants ## Invariants
- **No listener, no ports, no localhost.** After a transport change, - **No listener, no ports, no localhost.** After a transport change,
+3 -1
View File
@@ -2,7 +2,8 @@
#define YETANO_WINDOW_DARWIN_H #define YETANO_WINDOW_DARWIN_H
#include <stdint.h> #include <stdint.h>
void *yt_create(uintptr_t goHandle, const char *title, int width, int height, int debug, const char *scheme); void *yt_create(uintptr_t goHandle, const char *title, int width, int height, int debug, const char *scheme,
int hasFrame, int fx, int fy, int fw, int fh, int zoomed);
void yt_add_script(void *h, const char *js); void yt_add_script(void *h, const char *js);
void yt_navigate(void *h, const char *url); void yt_navigate(void *h, const char *url);
void yt_eval(void *h, const char *js); void yt_eval(void *h, const char *js);
@@ -17,5 +18,6 @@ void yt_snapshot(void *h, const char *path);
void yt_set_appearance(void *h, int mode); void yt_set_appearance(void *h, int mode);
void yt_accent_color(char *buf, int n); void yt_accent_color(char *buf, int n);
void yt_set_app_icon(const void *png, int n); void yt_set_app_icon(const void *png, int n);
void yt_file_dialog(void *h, int save, const char *title, const char *dir, const char *name, const char *types);
#endif #endif
+89 -3
View File
@@ -9,6 +9,7 @@
// marshalled with dispatch_async onto the main queue. // marshalled with dispatch_async onto the main queue.
#import <Cocoa/Cocoa.h> #import <Cocoa/Cocoa.h>
#import <WebKit/WebKit.h> #import <WebKit/WebKit.h>
#import <UniformTypeIdentifiers/UniformTypeIdentifiers.h>
#include "darwin.h" #include "darwin.h"
// Implemented in Go (window_darwin.go). // Implemented in Go (window_darwin.go).
@@ -18,6 +19,18 @@ extern void ytGoSchemeStop(uintptr_t h, long id);
extern void ytGoDispatch(uintptr_t fn); extern void ytGoDispatch(uintptr_t fn);
extern void ytGoClosed(uintptr_t h); extern void ytGoClosed(uintptr_t h);
extern void ytGoSnapshotDone(uintptr_t h, const char *err); extern void ytGoSnapshotDone(uintptr_t h, const char *err);
extern void ytGoFrame(uintptr_t h, int x, int y, int w, int hgt, int zoomed);
extern void ytGoFileDone(uintptr_t h, const char *path);
// YTWebView takes the first mouse click in an inactive window: without
// it the click only activates the window, so a page (a dialog shown at
// start) looks dead until clicked twice.
@interface YTWebView : WKWebView
@end
@implementation YTWebView
- (BOOL)acceptsFirstMouse:(NSEvent *)event { return YES; }
@end
@interface YTHost : NSObject <WKScriptMessageHandler, WKURLSchemeHandler, NSWindowDelegate> @interface YTHost : NSObject <WKScriptMessageHandler, WKURLSchemeHandler, NSWindowDelegate>
@property (assign) uintptr_t goHandle; @property (assign) uintptr_t goHandle;
@@ -26,6 +39,7 @@ extern void ytGoSnapshotDone(uintptr_t h, const char *err);
@property (strong) NSMutableDictionary<NSNumber *, id<WKURLSchemeTask>> *tasks; @property (strong) NSMutableDictionary<NSNumber *, id<WKURLSchemeTask>> *tasks;
@property (assign) long nextTask; @property (assign) long nextTask;
@property (assign) BOOL closed; @property (assign) BOOL closed;
@property (assign) NSRect normalFrame; // the last frame while not zoomed
@end @end
@implementation YTHost @implementation YTHost
@@ -67,7 +81,21 @@ extern void ytGoSnapshotDone(uintptr_t h, const char *err);
ytGoSchemeStop(self.goHandle, key.longValue); ytGoSchemeStop(self.goHandle, key.longValue);
} }
// The frame is reported after every move and resize; while zoomed, the
// normal frame underneath is kept, so un-zooming returns to it.
- (void)reportFrame {
if (self.closed || !self.window) return;
BOOL zoomed = self.window.isZoomed;
if (!zoomed) self.normalFrame = self.window.frame;
NSRect f = self.normalFrame;
if (f.size.width <= 0) return;
ytGoFrame(self.goHandle, (int)f.origin.x, (int)f.origin.y, (int)f.size.width, (int)f.size.height, zoomed ? 1 : 0);
}
- (void)windowDidMove:(NSNotification *)n { [self reportFrame]; }
- (void)windowDidResize:(NSNotification *)n { [self reportFrame]; }
- (void)windowWillClose:(NSNotification *)n { - (void)windowWillClose:(NSNotification *)n {
[self reportFrame];
if (self.closed) return; if (self.closed) return;
ytGoClosed(self.goHandle); ytGoClosed(self.goHandle);
yt_stop(); yt_stop();
@@ -102,7 +130,19 @@ static void ensureApp(void) {
[NSApp finishLaunching]; [NSApp finishLaunching];
} }
void *yt_create(uintptr_t goHandle, const char *title, int width, int height, int debug, const char *scheme) { // onScreen: at least a 120 x 60 point piece of the frame (with its title
// bar) is on a connected screen -- a frame saved on a display that is
// gone is not restored off screen.
static BOOL onScreen(NSRect f) {
for (NSScreen *s in [NSScreen screens]) {
NSRect i = NSIntersectionRect(f, s.visibleFrame);
if (i.size.width >= 120 && i.size.height >= 60) return YES;
}
return NO;
}
void *yt_create(uintptr_t goHandle, const char *title, int width, int height, int debug, const char *scheme,
int hasFrame, int fx, int fy, int fw, int fh, int zoomed) {
@autoreleasepool { @autoreleasepool {
ensureApp(); ensureApp();
YTHost *host = [YTHost new]; YTHost *host = [YTHost new];
@@ -115,7 +155,7 @@ void *yt_create(uintptr_t goHandle, const char *title, int width, int height, in
if (debug) [cfg.preferences setValue:@YES forKey:@"developerExtrasEnabled"]; if (debug) [cfg.preferences setValue:@YES forKey:@"developerExtrasEnabled"];
NSRect frame = NSMakeRect(0, 0, width, height); NSRect frame = NSMakeRect(0, 0, width, height);
host.webview = [[WKWebView alloc] initWithFrame:frame configuration:cfg]; host.webview = [[YTWebView alloc] initWithFrame:frame configuration:cfg];
if (@available(macOS 13.3, *)) { if (debug) host.webview.inspectable = YES; } if (@available(macOS 13.3, *)) { if (debug) host.webview.inspectable = YES; }
host.window = [[NSWindow alloc] initWithContentRect:frame host.window = [[NSWindow alloc] initWithContentRect:frame
@@ -126,9 +166,17 @@ void *yt_create(uintptr_t goHandle, const char *title, int width, int height, in
host.window.releasedWhenClosed = NO; host.window.releasedWhenClosed = NO;
host.window.title = str(title); host.window.title = str(title);
host.window.contentView = host.webview; host.window.contentView = host.webview;
NSRect saved = NSMakeRect(fx, fy, fw, fh);
BOOL restore = hasFrame && onScreen(saved);
if (restore) {
[host.window setFrame:saved display:NO];
} else {
[host.window center];
}
host.normalFrame = host.window.frame;
host.window.delegate = host; host.window.delegate = host;
[host.window center];
[host.window makeKeyAndOrderFront:nil]; [host.window makeKeyAndOrderFront:nil];
if (restore && zoomed && !host.window.isZoomed) [host.window zoom:nil];
[NSApp activateIgnoringOtherApps:YES]; [NSApp activateIgnoringOtherApps:YES];
return (__bridge_retained void *)host; return (__bridge_retained void *)host;
} }
@@ -171,6 +219,7 @@ void yt_stop(void) {
void yt_destroy(void *h) { void yt_destroy(void *h) {
YTHost *host = (__bridge_transfer YTHost *)h; // balances __bridge_retained YTHost *host = (__bridge_transfer YTHost *)h; // balances __bridge_retained
[host reportFrame]; // a window ended by Terminate, not closed by the user
host.closed = YES; host.closed = YES;
for (NSNumber *k in host.tasks.allKeys) { for (NSNumber *k in host.tasks.allKeys) {
// Remaining tasks are failed so WebKit does not wait forever. // Remaining tasks are failed so WebKit does not wait forever.
@@ -280,3 +329,40 @@ void yt_set_app_icon(const void *png, int n) {
if (img) NSApp.applicationIconImage = img; if (img) NSApp.applicationIconImage = img;
} }
} }
// --- file dialogs ------------------------------------------------------------
// yt_file_dialog shows an open (save = 0) or save panel as a sheet on the
// window. dir: the folder to start in, name: a save panel's suggested file
// name, types: allowed file extensions, comma-separated ("" = any). The
// chosen path, or NULL when cancelled, goes to ytGoFileDone.
void yt_file_dialog(void *h, int save, const char *title, const char *dir, const char *name, const char *types) {
YTHost *host = (__bridge YTHost *)h;
uintptr_t gh = host.goHandle;
NSSavePanel *panel;
if (save) {
panel = [NSSavePanel savePanel];
if (name && name[0]) panel.nameFieldStringValue = str(name);
} else {
NSOpenPanel *open = [NSOpenPanel openPanel];
open.canChooseFiles = YES;
open.canChooseDirectories = NO;
open.allowsMultipleSelection = NO;
open.resolvesAliases = YES;
panel = open;
}
if (title && title[0]) { panel.title = str(title); panel.message = str(title); }
if (dir && dir[0]) panel.directoryURL = [NSURL fileURLWithPath:str(dir) isDirectory:YES];
if (types && types[0]) {
NSMutableArray<UTType *> *uts = [NSMutableArray array];
for (NSString *ext in [str(types) componentsSeparatedByString:@","]) {
UTType *t = [UTType typeWithFilenameExtension:ext];
if (t) [uts addObject:t];
}
if (uts.count) panel.allowedContentTypes = uts;
}
[panel beginSheetModalForWindow:host.window completionHandler:^(NSModalResponse r) {
if (r != NSModalResponseOK || !panel.URL) { ytGoFileDone(gh, NULL); return; }
ytGoFileDone(gh, panel.URL.path.fileSystemRepresentation);
}];
}
+115
View File
@@ -0,0 +1,115 @@
//go:build windows
package window
import (
"fmt"
"strings"
"unsafe"
"golang.org/x/sys/windows"
)
var (
comdlg32 = windows.NewLazySystemDLL("comdlg32.dll")
pGetOpenFile = comdlg32.NewProc("GetOpenFileNameW")
pGetSaveFile = comdlg32.NewProc("GetSaveFileNameW")
pCommDlgExtErr = comdlg32.NewProc("CommDlgExtendedError")
errNoFileDialog = fmt.Errorf("window: file dialog failed")
)
// openFileName is OPENFILENAMEW (commdlg.h).
type openFileName struct {
lStructSize uint32
hwndOwner uintptr
hInstance uintptr
lpstrFilter *uint16
lpstrCustomFilter *uint16
nMaxCustFilter uint32
nFilterIndex uint32
lpstrFile *uint16
nMaxFile uint32
lpstrFileTitle *uint16
nMaxFileTitle uint32
lpstrInitialDir *uint16
lpstrTitle *uint16
flags uint32
nFileOffset uint16
nFileExtension uint16
lpstrDefExt *uint16
lCustData uintptr
lpfnHook uintptr
lpTemplateName *uint16
pvReserved uintptr
dwReserved uint32
flagsEx uint32
}
const (
ofnOverwritePrompt = 0x00000002
ofnNoChangeDir = 0x00000008
ofnPathMustExist = 0x00000800
ofnFileMustExist = 0x00001000
ofnExplorer = 0x00080000
)
// fileFilter is the dialog's filter list: the allowed extensions, then
// all files; pairs of display text and pattern, each NUL-terminated,
// the list ending with an extra NUL.
func fileFilter(exts []string) []uint16 {
var b strings.Builder
if len(exts) > 0 {
pats := make([]string, len(exts))
for i, e := range exts {
pats[i] = "*." + strings.TrimPrefix(e, ".")
}
p := strings.Join(pats, ";")
b.WriteString(p + " (" + p + ")\x00" + p + "\x00")
}
b.WriteString("All files (*.*)\x00*.*\x00\x00")
return windows.StringToUTF16(b.String())
}
// FileDialog shows the common open or save dialog, modal to the window
// (it runs its own message loop on the UI thread); done runs right after.
func (b *winBackend) FileDialog(d FileDialog, done func(string, error)) {
buf := make([]uint16, 32768)
if d.Save && d.Name != "" {
copy(buf[:len(buf)-1], windows.StringToUTF16(d.Name))
}
filter := fileFilter(d.Extensions)
ofn := openFileName{
hwndOwner: b.hwnd,
lpstrFilter: &filter[0],
nFilterIndex: 1,
lpstrFile: &buf[0],
nMaxFile: uint32(len(buf)),
flags: ofnExplorer | ofnNoChangeDir | ofnPathMustExist,
}
ofn.lStructSize = uint32(unsafe.Sizeof(ofn))
if d.Title != "" {
ofn.lpstrTitle, _ = windows.UTF16PtrFromString(d.Title)
}
if d.Directory != "" {
ofn.lpstrInitialDir, _ = windows.UTF16PtrFromString(d.Directory)
}
proc := pGetOpenFile
if d.Save {
proc = pGetSaveFile
ofn.flags |= ofnOverwritePrompt
if len(d.Extensions) > 0 {
ofn.lpstrDefExt, _ = windows.UTF16PtrFromString(strings.TrimPrefix(d.Extensions[0], "."))
}
} else {
ofn.flags |= ofnFileMustExist
}
if r, _, _ := proc.Call(uintptr(unsafe.Pointer(&ofn))); r == 0 {
if code, _, _ := pCommDlgExtErr.Call(); code != 0 {
done("", fmt.Errorf("%w: CommDlgExtendedError 0x%x", errNoFileDialog, code))
return
}
done("", nil) // cancelled
return
}
done(windows.UTF16ToString(buf), nil)
}
+22
View File
@@ -0,0 +1,22 @@
//go:build windows
package window
import "testing"
func TestFileFilter(t *testing.T) {
raw := fileFilter([]string{"pdf", ".txt"})
s := string(utf16Runes(raw))
want := "*.pdf;*.txt (*.pdf;*.txt)\x00*.pdf;*.txt\x00All files (*.*)\x00*.*\x00\x00\x00"
if s != want {
t.Errorf("filter = %q, want %q", s, want)
}
}
func utf16Runes(u []uint16) []rune {
r := make([]rune, len(u))
for i, c := range u {
r[i] = rune(c)
}
return r
}
+116
View File
@@ -0,0 +1,116 @@
package window
import (
"encoding/json"
"os"
"path/filepath"
"sync"
"time"
)
// Frame is a window's position and size in the platform's own screen
// coordinates (macOS: points, origin bottom left; Windows: pixels of the
// virtual screen, origin top left). It is only ever read back on the
// platform that wrote it. Maximized (macOS: zoomed) keeps the normal
// frame underneath, so un-maximizing returns to it.
type Frame struct {
X int `json:"x"`
Y int `json:"y"`
Width int `json:"width"`
Height int `json:"height"`
Maximized bool `json:"maximized,omitempty"`
}
// minFrame is the smallest frame restored; anything smaller is a broken
// file, not a window someone made.
const minFrame = 200
func (f Frame) usable() bool { return f.Width >= minFrame && f.Height >= minFrame }
// loadFrame reads a frame file written by frameSaver. A missing,
// unreadable or implausible file is no frame: the window opens with its
// default size, centered.
func loadFrame(path string) (Frame, bool) {
if path == "" {
return Frame{}, false
}
data, err := os.ReadFile(path)
if err != nil {
return Frame{}, false
}
var f Frame
if json.Unmarshal(data, &f) != nil || !f.usable() {
return Frame{}, false
}
return f, true
}
// frameSaver writes the window's frame to its file, a moment after the
// last move or resize (a drag reports many), and once more at Destroy.
type frameSaver struct {
path string
mu sync.Mutex
last Frame
dirty bool
timer *time.Timer
}
const frameSaveDelay = 400 * time.Millisecond
func (s *frameSaver) changed(f Frame) {
if s == nil || !f.usable() {
return
}
s.mu.Lock()
defer s.mu.Unlock()
if f == s.last && !s.dirty {
return
}
s.last, s.dirty = f, true
if s.timer == nil {
s.timer = time.AfterFunc(frameSaveDelay, s.flush)
} else {
s.timer.Reset(frameSaveDelay)
}
}
// flush writes a pending frame (temp file + rename, so a crash never
// leaves half a file). Errors are not fatal: the next start just opens
// with the default frame.
func (s *frameSaver) flush() {
if s == nil {
return
}
s.mu.Lock()
if s.timer != nil {
s.timer.Stop()
}
f, dirty := s.last, s.dirty
s.dirty = false
s.mu.Unlock()
if !dirty {
return
}
data, err := json.Marshal(f)
if err != nil {
return
}
if err := os.MkdirAll(filepath.Dir(s.path), 0o755); err != nil {
debugf("window: frame file: %v", err)
return
}
tmp := s.path + ".tmp"
if err := os.WriteFile(tmp, append(data, '\n'), 0o644); err != nil {
debugf("window: frame file: %v", err)
return
}
if err := os.Rename(tmp, s.path); err != nil {
debugf("window: frame file: %v", err)
}
}
func debugf(format string, args ...any) {
if Debugf != nil {
Debugf(format, args...)
}
}
+40
View File
@@ -0,0 +1,40 @@
package window
import (
"os"
"path/filepath"
"testing"
)
func TestFrameFileRoundTrip(t *testing.T) {
path := filepath.Join(t.TempDir(), "state", "window.json")
if _, ok := loadFrame(path); ok {
t.Fatal("a missing file is a frame")
}
s := &frameSaver{path: path}
s.changed(Frame{X: 10, Y: 20, Width: 300, Height: 200})
s.changed(Frame{X: 40, Y: 50, Width: 1200, Height: 800, Maximized: true}) // the last one wins
s.flush()
f, ok := loadFrame(path)
if !ok || f != (Frame{X: 40, Y: 50, Width: 1200, Height: 800, Maximized: true}) {
t.Fatalf("loaded %+v, %v", f, ok)
}
if _, err := os.Stat(path + ".tmp"); !os.IsNotExist(err) {
t.Errorf("temp file left behind: %v", err)
}
// Too small or broken: no frame, the window opens with its default.
for _, data := range []string{`{"x":0,"y":0,"width":50,"height":40}`, `not json`, ``} {
if err := os.WriteFile(path, []byte(data), 0o644); err != nil {
t.Fatal(err)
}
if f, ok := loadFrame(path); ok {
t.Errorf("%q loaded as %+v", data, f)
}
}
s.changed(Frame{Width: 10, Height: 10}) // ignored
s.flush()
if data, _ := os.ReadFile(path); string(data) != "" {
t.Errorf("an unusable frame was written: %q", data)
}
}
+79 -1
View File
@@ -53,6 +53,16 @@ type Options struct {
DataPath string // WebView2 user data folder (Windows) DataPath string // WebView2 user data folder (Windows)
OnMessage func(msg string) OnMessage func(msg string)
Resource ResourceHandler // nil: no native resource handler Resource ResourceHandler // nil: no native resource handler
// FrameFile, if set, keeps the window's position and size across
// starts: read at New (a frame that is no longer on any screen is
// ignored), written a moment after every move or resize and at
// Destroy. A small JSON file (Frame); the program picks the path,
// e.g. in its state directory.
FrameFile string
// Set by New for the backend.
restore *Frame // the frame to open with, nil: default, centered
onFrame func(Frame) // the backend reports a moved or resized window
} }
type backend interface { type backend interface {
@@ -67,6 +77,7 @@ type backend interface {
// Window is a guarded native WebView window. // Window is a guarded native WebView window.
type Window struct { type Window struct {
frames *frameSaver
mu sync.Mutex mu sync.Mutex
b backend b backend
alive bool alive bool
@@ -92,11 +103,20 @@ func New(opt Options) (*Window, error) {
if opt.Width == 0 { if opt.Width == 0 {
opt.Width, opt.Height = 1100, 820 opt.Width, opt.Height = 1100, 820
} }
var frames *frameSaver
if opt.FrameFile != "" {
frames = &frameSaver{path: opt.FrameFile}
if f, ok := loadFrame(opt.FrameFile); ok {
opt.restore = &f
frames.last = f
}
opt.onFrame = frames.changed
}
b, name, base, err := newBackend(opt) b, name, base, err := newBackend(opt)
if err != nil { if err != nil {
return nil, err return nil, err
} }
return &Window{b: b, alive: true, name: name, base: base}, nil return &Window{b: b, alive: true, name: name, base: base, frames: frames}, nil
} }
// Backend names the native backend. // Backend names the native backend.
@@ -156,6 +176,7 @@ func (w *Window) Destroy() {
w.alive = false w.alive = false
w.mu.Unlock() w.mu.Unlock()
w.b.Destroy() w.b.Destroy()
w.frames.flush()
} }
// snapshotter is implemented by backends that can render the page to PNG. // snapshotter is implemented by backends that can render the page to PNG.
@@ -198,6 +219,63 @@ func SetAppIcon(png []byte) { setAppIcon(png) }
// unknown. Safe to call before a window exists. // unknown. Safe to call before a window exists.
func AccentColor() string { return accentColor() } func AccentColor() string { return accentColor() }
// FileDialog describes a native open or save dialog.
type FileDialog struct {
Save bool // a save dialog; otherwise open one existing file
Title string // the prompt; "" for the system's
Directory string // the folder to start in; "" for the system's choice
Name string // save: the suggested file name
Extensions []string // allowed extensions without the dot ("pdf"); empty: any file
}
// ErrDialogOpen: a file dialog of this window is already open.
var ErrDialogOpen = errors.New("window: a file dialog is already open")
// fileDialoger is implemented by backends with native file dialogs.
type fileDialoger interface {
FileDialog(d FileDialog, done func(path string, err error))
}
// ShowFileDialog shows a native open or save dialog for the window (UI
// thread; one at a time). done runs on the UI thread with the chosen
// path, or "" and a nil error when the user cancelled. A save dialog
// has asked about replacing an existing file already; nothing is read
// or written here -- that is the program's choice.
func (w *Window) ShowFileDialog(d FileDialog, done func(path string, err error)) {
f, ok := w.b.(fileDialoger)
if !ok {
done("", errors.New("window: file dialogs not supported by "+w.name))
return
}
f.FileDialog(d, done)
}
// ChooseFile shows a file dialog from any goroutine and waits for the
// user: the chosen path, or "" and nil when cancelled. ctx ending (the
// request was dropped) stops the wait, not the dialog.
func (w *Window) ChooseFile(ctx context.Context, d FileDialog) (string, error) {
type result struct {
path string
err error
}
ch := make(chan result, 1)
w.mu.Lock()
alive := w.alive
w.mu.Unlock()
if !alive {
return "", errors.New("window: destroyed")
}
w.Dispatch(func() {
w.ShowFileDialog(d, func(p string, err error) { ch <- result{p, err} })
})
select {
case r := <-ch:
return r.path, r.err
case <-ctx.Done():
return "", ctx.Err()
}
}
// DroppedDispatches counts Dispatch calls that arrived after Destroy. // DroppedDispatches counts Dispatch calls that arrived after Destroy.
func (w *Window) DroppedDispatches() int { func (w *Window) DroppedDispatches() int {
w.mu.Lock() w.mu.Lock()
+67 -2
View File
@@ -4,7 +4,7 @@ package window
/* /*
#cgo CFLAGS: -x objective-c -fobjc-arc #cgo CFLAGS: -x objective-c -fobjc-arc
#cgo LDFLAGS: -framework Cocoa -framework WebKit #cgo LDFLAGS: -framework Cocoa -framework WebKit -framework UniformTypeIdentifiers
#include <stdlib.h> #include <stdlib.h>
#include "darwin.h" #include "darwin.h"
*/ */
@@ -16,6 +16,7 @@ import (
"net/http" "net/http"
"runtime" "runtime"
"runtime/cgo" "runtime/cgo"
"strings"
"sync" "sync"
"unsafe" "unsafe"
) )
@@ -35,6 +36,7 @@ type darwinBackend struct {
mu sync.RWMutex // guards h against Destroy while a goroutine calls into ObjC mu sync.RWMutex // guards h against Destroy while a goroutine calls into ObjC
snapDone func(error) snapDone func(error)
fileDone func(path string, err error)
} }
// with runs f with the live host pointer, or not at all after Destroy. // with runs f with the live host pointer, or not at all after Destroy.
@@ -63,7 +65,16 @@ func newBackend(opt Options) (backend, string, string, error) {
if opt.Debug { if opt.Debug {
debug = 1 debug = 1
} }
b.h = C.yt_create(C.uintptr_t(b.handle), title, C.int(opt.Width), C.int(opt.Height), C.int(debug), scheme) var has, zoomed C.int
var f Frame
if opt.restore != nil {
has, f = 1, *opt.restore
if f.Maximized {
zoomed = 1
}
}
b.h = C.yt_create(C.uintptr_t(b.handle), title, C.int(opt.Width), C.int(opt.Height), C.int(debug), scheme,
has, C.int(f.X), C.int(f.Y), C.int(f.Width), C.int(f.Height), zoomed)
if b.h == nil { if b.h == nil {
b.handle.Delete() b.handle.Delete()
return nil, "", "", errUnavailable("WKWebView could not be created") return nil, "", "", errUnavailable("WKWebView could not be created")
@@ -122,6 +133,14 @@ func ytGoDispatch(fn C.uintptr_t) {
f() f()
} }
//export ytGoFrame
func ytGoFrame(h C.uintptr_t, x, y, w, hgt, zoomed C.int) {
b := cgo.Handle(h).Value().(*darwinBackend)
if b.opt.onFrame != nil {
b.opt.onFrame(Frame{X: int(x), Y: int(y), Width: int(w), Height: int(hgt), Maximized: zoomed != 0})
}
}
//export ytGoMessage //export ytGoMessage
func ytGoMessage(h C.uintptr_t, msg *C.char) { func ytGoMessage(h C.uintptr_t, msg *C.char) {
b := cgo.Handle(h).Value().(*darwinBackend) b := cgo.Handle(h).Value().(*darwinBackend)
@@ -281,3 +300,49 @@ func (t *darwinTask) Close(err error) {
} }
t.b.with(func(h unsafe.Pointer) { C.yt_task_finish(h, C.long(t.id), ce) }) t.b.with(func(h unsafe.Pointer) { C.yt_task_finish(h, C.long(t.id), ce) })
} }
// FileDialog shows a native open or save panel as a sheet on the window;
// done runs on the UI thread.
func (b *darwinBackend) FileDialog(d FileDialog, done func(string, error)) {
b.mu.Lock()
if b.fileDone != nil {
b.mu.Unlock()
done("", ErrDialogOpen)
return
}
b.fileDone = done
b.mu.Unlock()
save := 0
if d.Save {
save = 1
}
title, dir, name, types := cstr(d.Title), cstr(d.Directory), cstr(d.Name), cstr(strings.Join(d.Extensions, ","))
defer func() {
for _, c := range []*C.char{title, dir, name, types} {
C.free(unsafe.Pointer(c))
}
}()
if !b.with(func(h unsafe.Pointer) { C.yt_file_dialog(h, C.int(save), title, dir, name, types) }) {
b.mu.Lock()
b.fileDone = nil
b.mu.Unlock()
done("", errUnavailable("file dialog: the window is gone"))
}
}
//export ytGoFileDone
func ytGoFileDone(h C.uintptr_t, path *C.char) {
b := cgo.Handle(h).Value().(*darwinBackend)
b.mu.Lock()
done := b.fileDone
b.fileDone = nil
b.mu.Unlock()
if done == nil {
return
}
if path == nil {
done("", nil)
return
}
done(C.GoString(path), nil)
}
+61 -1
View File
@@ -56,6 +56,9 @@ var (
pDwmSetAttribute = dwmapi.NewProc("DwmSetWindowAttribute") pDwmSetAttribute = dwmapi.NewProc("DwmSetWindowAttribute")
pSetWindowPos = user32.NewProc("SetWindowPos") pSetWindowPos = user32.NewProc("SetWindowPos")
pGetDpiForSystem = user32.NewProc("GetDpiForSystem") pGetDpiForSystem = user32.NewProc("GetDpiForSystem")
pGetPlacement = user32.NewProc("GetWindowPlacement")
pSetPlacement = user32.NewProc("SetWindowPlacement")
pMonitorFromRect = user32.NewProc("MonitorFromRect")
) )
func setAppIcon([]byte) {} // the icon comes from the .exe resources (RT_GROUP_ICON "APP") func setAppIcon([]byte) {} // the icon comes from the .exe resources (RT_GROUP_ICON "APP")
@@ -168,7 +171,9 @@ func newBackend(opt Options) (backend, string, string, error) {
windowsMu.Lock() windowsMu.Lock()
byHWND[hwnd] = b byHWND[hwnd] = b
windowsMu.Unlock() windowsMu.Unlock()
pShowWindow.Call(hwnd, swShow) if f := opt.restore; f == nil || !restorePlacement(hwnd, *f) {
pShowWindow.Call(hwnd, swShow)
}
pUpdateWindow.Call(hwnd) pUpdateWindow.Call(hwnd)
pSetFocus.Call(hwnd) pSetFocus.Call(hwnd)
@@ -209,14 +214,17 @@ func wndproc(hwnd, msg, wp, lp uintptr) uintptr {
if b.chromium != nil { if b.chromium != nil {
b.chromium.Resize() b.chromium.Resize()
} }
b.reportFrame()
case wmMove, wmMoving: case wmMove, wmMoving:
if b.chromium != nil { if b.chromium != nil {
_ = b.chromium.NotifyParentWindowPositionChanged() _ = b.chromium.NotifyParentWindowPositionChanged()
} }
b.reportFrame()
case wmApp: case wmApp:
b.runQueue() b.runQueue()
return 0 return 0
case wmClose: case wmClose:
b.reportFrame()
pDestroyWindow.Call(hwnd) pDestroyWindow.Call(hwnd)
return 0 return 0
case wmDestroy: case wmDestroy:
@@ -233,6 +241,57 @@ func wndproc(hwnd, msg, wp, lp uintptr) uintptr {
return r return r
} }
// windowPlacement is WINDOWPLACEMENT. rcNormalPosition is the restored
// (not maximized) frame in workspace coordinates; Get and Set use the
// same ones, so a saved frame comes back where it was.
type windowPlacement struct {
length uint32
flags uint32
showCmd uint32
ptMinPosition [2]int32
ptMaxPosition [2]int32
rcNormalPosition [4]int32 // left, top, right, bottom
}
const (
swShowNormal = 1
swShowMinimized = 2
swShowMaximized = 3
wpfRestoreToMaximize = 0x0002
)
// reportFrame hands the window's normal frame and maximized state to
// Options.FrameFile's saver.
func (b *winBackend) reportFrame() {
if b.opt.onFrame == nil {
return
}
var wp windowPlacement
wp.length = uint32(unsafe.Sizeof(wp))
if r, _, _ := pGetPlacement.Call(b.hwnd, uintptr(unsafe.Pointer(&wp))); r == 0 {
return
}
rc := wp.rcNormalPosition
maximized := wp.showCmd == swShowMaximized || (wp.showCmd == swShowMinimized && wp.flags&wpfRestoreToMaximize != 0)
b.opt.onFrame(Frame{X: int(rc[0]), Y: int(rc[1]), Width: int(rc[2] - rc[0]), Height: int(rc[3] - rc[1]), Maximized: maximized})
}
// restorePlacement shows the window with a saved frame, when that frame
// is still on a monitor (MONITOR_DEFAULTTONULL); false: show it as new.
func restorePlacement(hwnd uintptr, f Frame) bool {
rc := [4]int32{int32(f.X), int32(f.Y), int32(f.X + f.Width), int32(f.Y + f.Height)}
if m, _, _ := pMonitorFromRect.Call(uintptr(unsafe.Pointer(&rc)), 0); m == 0 {
return false
}
wp := windowPlacement{showCmd: swShowNormal, rcNormalPosition: rc}
if f.Maximized {
wp.showCmd = swShowMaximized
}
wp.length = uint32(unsafe.Sizeof(wp))
r, _, _ := pSetPlacement.Call(hwnd, uintptr(unsafe.Pointer(&wp)))
return r != 0
}
func (b *winBackend) runQueue() { func (b *winBackend) runQueue() {
b.mu.Lock() b.mu.Lock()
q := b.queue q := b.queue
@@ -277,6 +336,7 @@ func (b *winBackend) Destroy() {
b.destroying = true b.destroying = true
b.mu.Unlock() b.mu.Unlock()
if ok, _, _ := pIsWindow.Call(b.hwnd); ok != 0 { if ok, _, _ := pIsWindow.Call(b.hwnd); ok != 0 {
b.reportFrame() // a window ended by Terminate, not closed by the user
pDestroyWindow.Call(b.hwnd) pDestroyWindow.Call(b.hwnd)
} }
windowsMu.Lock() windowsMu.Lock()
+35 -7
View File
@@ -1,18 +1,22 @@
# yetano.dev/yetano/core/trust # yetano.dev/yetano/core/trust
The verifying half of the family's publisher signatures, shared by every The family's minisign (Ed25519) signatures: verifying, shared by every
program that pulls signed content: yet (packages) and yacota (images) program that pulls signed content -- yet (packages) and yacota (images)
check against the same files, so a host makes one trust decision. check against the same files, so a host makes one trust decision -- and
signing, shared by every program that signs: yet (packages,
attestations) and yabar (evidence records, ADR-0037 there).
```text ```text
module yetano.dev/yetano/core/trust tags: trust/v0.1.0, ... go 1.25 module yetano.dev/yetano/core/trust tags: trust/v0.1.0, trust/v0.2.0, ... go 1.25
``` ```
A nested module of the core repository, like `core/tui`, so the main core A nested module of the core repository, like `core/tui`, so the main core
module stays free of minisign. Depends on `aead.dev/minisign` (MIT) and module stays free of minisign. Depends on `aead.dev/minisign` (MIT) and
core (`core/paths`, for `Home`). Moved from `yet/internal/trust` core (`core/paths`, for `Home`; `core/secretref`, for `KeyFromRef`).
(2026-11-12) without changing behavior or file formats; signing, key Moved from `yet/internal/trust` without changing behavior or file
storage, PEM and the registry side stay in yet. formats: the verifying half on 2026-11-12 (trust/v0.1.0), the signing
half on 2026-11-27 (trust/v0.2.0). Pushing signatures to a registry and
where auto-sign keeps its keys stay in yet.
## What it is ## What it is
@@ -33,6 +37,22 @@ storage, PEM and the registry side stay in yet.
- **Where:** `Home(scope)` is yet's data directory (core/paths' DataDir - **Where:** `Home(scope)` is yet's data directory (core/paths' DataDir
for "yet"), `DefaultPolicyPath(home)`, `DefaultKnownKeysPath(home)`. for "yet"), `DefaultPolicyPath(home)`, `DefaultKnownKeysPath(home)`.
- **Keys:** `KeyPair`, `GenerateKey`, `SaveKeyPair(path, kp, password)`
(private key owner-only, `<path>.pub` beside it; the minisign CLI's
formats, scrypt-encrypted with a password), `LoadPrivateKey`,
`ParsePrivateKey`, `LoadPublicKey`, `MarshalPublicKey`, and
`KeyFromRef(ctx, resolver, keyRef, passwordRef)` for a key held as a
secret reference (`secret://...` in yaseva, `env:`, `file:`).
- **Signing:** `SignDigest(kp, digest)` makes the package signature
`VerifySignature` checks; `Sign(kp, message, trustedComment,
untrustedComment)` makes a detached `.minisig` over any bytes, and
`VerifyMessage(pub, message, sig)` checks it and returns the trusted
comment (`minisign -Vm` checks it too); `SignEd25519`/`VerifyEd25519`
are plain Ed25519 for DSSE envelopes; `ExportPEM`/`ImportPEM` for
cosign and openssl.
- **Vector:** `testdata/sign-vector.*` -- a published test key, a
message and its signature; every version must produce and accept it.
## Use ## Use
```go ```go
@@ -45,5 +65,13 @@ policy, _ := trust.LoadPolicy(trust.DefaultPolicyPath(home))
if d := policy.Evaluate(name, kind, verified); !d.Trusted { ... } if d := policy.Evaluate(name, kind, verified); !d.Trusted { ... }
``` ```
Signing:
```go
kp, err := trust.KeyFromRef(ctx, secretref.New(""), "secret://yabar/evidence/minisign", "")
sig, err := trust.Sign(kp, recordBytes, "yabar evidence <test_id> <repository_id>", "")
comment, err := trust.VerifyMessage(pub, recordBytes, sig)
```
`Warn` (a variable) reports warnings that are not errors, on standard `Warn` (a variable) reports warnings that are not errors, on standard
error by default. error by default.
+191
View File
@@ -0,0 +1,191 @@
package trust
// The signing half of publisher signatures, moved from yet's
// internal/trust (2026-11-27, YABAR-036a) without changing behavior or
// file formats: key pairs in minisign's own file formats, the package
// signature over an OCI digest (SignDigest), detached signatures over
// any bytes (Sign, VerifyMessage), plain Ed25519 for DSSE envelopes,
// and PEM for cosign and openssl. Where keys are kept for auto-signing
// and pushing signatures to a registry stay in yet.
import (
"bytes"
"crypto"
"crypto/ed25519"
"crypto/sha512"
"fmt"
"os"
"path/filepath"
"aead.dev/minisign"
)
// KeyPair is a minisign key pair. The private key never leaves the host's
// filesystem; only the public key is shared with other hosts (as a plain
// ".pub" file) and embedded in signatures.
type KeyPair struct {
Public minisign.PublicKey
Private minisign.PrivateKey
}
// GenerateKey creates a new minisign key pair.
func GenerateKey() (KeyPair, error) {
pub, priv, err := minisign.GenerateKey(nil)
if err != nil {
return KeyPair{}, err
}
return KeyPair{Public: pub, Private: priv}, nil
}
// SaveKeyPair writes kp's private key to path (owner-only permissions) and
// its public key to path+".pub" (world-readable: it is meant to be shared).
// This mirrors the real minisign CLI's `-p file.pub -s file` convention, so
// `trust policy allow` only ever needs the ".pub" file, never the private
// key -- a relying party registering a publisher's trust never needs (and
// should never be handed) their private key.
//
// If password is non-empty, the private key is scrypt-encrypted exactly as
// `minisign -G` with a passphrase would; if empty, it is written
// unencrypted, matching the minisign CLI's own behavior when a blank
// passphrase is given. Either way the file is only ever readable by its
// owner; a password additionally protects it if the file itself leaks.
func SaveKeyPair(path string, kp KeyPair, password string) error {
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
return err
}
var privData []byte
var err error
if password != "" {
privData, err = minisign.EncryptKey(password, kp.Private)
} else {
privData, err = kp.Private.MarshalText()
}
if err != nil {
return fmt.Errorf("encode private key: %w", err)
}
if err := writeOwnerOnly(path, privData); err != nil {
return err
}
pubData, err := MarshalPublicKey(kp.Public)
if err != nil {
return fmt.Errorf("encode public key: %w", err)
}
return writeFile(path+".pub", pubData, 0o644)
}
// LoadPrivateKey reads a key pair previously written by SaveKeyPair,
// decrypting it with password if it is encrypted (password is ignored, and
// may be empty, for an unencrypted key).
func LoadPrivateKey(path, password string) (KeyPair, error) {
data, err := os.ReadFile(path)
if err != nil {
return KeyPair{}, err
}
return ParsePrivateKey(data, password)
}
// ParsePrivateKey parses a minisign private key file's contents, the
// same bytes LoadPrivateKey reads from disk, so a key can also come from
// somewhere other than a file (a yaseva secret, see KeyStore).
func ParsePrivateKey(data []byte, password string) (KeyPair, error) {
var err error
var priv minisign.PrivateKey
if minisign.IsEncrypted(data) {
priv, err = minisign.DecryptKey(password, data)
if err != nil {
return KeyPair{}, fmt.Errorf("decrypt private key (wrong password?): %w", err)
}
} else if err := priv.UnmarshalText(data); err != nil {
return KeyPair{}, fmt.Errorf("parse private key: %w", err)
}
pub, ok := priv.Public().(minisign.PublicKey)
if !ok {
return KeyPair{}, fmt.Errorf("derive public key: unexpected type %T", priv.Public())
}
return KeyPair{Public: pub, Private: priv}, nil
}
// LoadPublicKey reads a standalone ".pub" file, for a trust policy that
// must never require (or accept) private key material.
func LoadPublicKey(path string) (minisign.PublicKey, error) {
return minisign.PublicKeyFromFile(path)
}
// MarshalPublicKey encodes pub as a minisign ".pub" file. It is
// aead.dev/minisign's own encoding, except that the comment line carries
// the 16-digit key ID (the library writes it without leading zeros).
func MarshalPublicKey(pub minisign.PublicKey) ([]byte, error) {
data, err := pub.MarshalText()
if err != nil {
return nil, err
}
_, rest, ok := bytes.Cut(data, []byte("\n"))
if !ok {
return data, nil
}
out := fmt.Appendf(nil, "untrusted comment: minisign public key: %s\n", ID(pub))
out = append(out, rest...)
if !bytes.HasSuffix(out, []byte("\n")) {
out = append(out, '\n')
}
return out, nil
}
func writeOwnerOnly(path string, data []byte) error {
return writeFile(path, data, 0o600)
}
func writeFile(path string, data []byte, mode os.FileMode) error {
tmp, err := os.CreateTemp(filepath.Dir(path), ".key-*")
if err != nil {
return err
}
defer func() { _ = os.Remove(tmp.Name()) }()
if err := os.Chmod(tmp.Name(), mode); err != nil {
_ = tmp.Close()
return err
}
if _, err := tmp.Write(data); err != nil {
_ = tmp.Close()
return err
}
if err := tmp.Close(); err != nil {
return err
}
return os.Rename(tmp.Name(), path)
}
// SignEd25519 signs message with kp as a plain Ed25519 signature
// (minisign's non-prehashed "Ed" algorithm): the raw 64 bytes DSSE
// envelopes carry and cosign and other Ed25519 verifiers check against
// ExportPEM's key. Package signatures (Sign) keep using minisign's own
// format.
func SignEd25519(kp KeyPair, message []byte) ([]byte, error) {
text, err := kp.Private.Sign(nil, message, crypto.Hash(0))
if err != nil {
return nil, err
}
var sig minisign.Signature
if err := sig.UnmarshalText(text); err != nil {
return nil, err
}
if sig.Algorithm != minisign.EdDSA {
return nil, fmt.Errorf("unexpected minisign algorithm %d", sig.Algorithm)
}
return sig.Signature[:], nil
}
// VerifyEd25519 checks an Ed25519 signature over message against pub:
// plain Ed25519 (what SignEd25519 makes) or Ed25519ph with SHA-512
// (what cosign makes with an Ed25519 key).
func VerifyEd25519(pub minisign.PublicKey, message, sig []byte) bool {
raw := Ed25519Key(pub)
if raw == nil || len(sig) != ed25519.SignatureSize {
return false
}
if ed25519.Verify(raw, message, sig) {
return true
}
digest := sha512.Sum512(message)
return ed25519.VerifyWithOptions(raw, digest[:], sig, &ed25519.Options{Hash: crypto.SHA512}) == nil
}
+90
View File
@@ -0,0 +1,90 @@
package trust
// Moved from yet's internal/trust with the signing half (2026-11-27).
import (
"crypto/ed25519"
"crypto/sha256"
"crypto/x509"
"encoding/base64"
"encoding/binary"
"encoding/pem"
"errors"
"fmt"
"strconv"
"aead.dev/minisign"
)
// ExportPEM encodes pub's Ed25519 key as a PEM "PUBLIC KEY" block
// (PKIX), the form cosign, openssl and most other tools read -- e.g.
// "cosign verify-attestation --key exported.pem". Only the key leaves:
// a PEM file has no room for minisign's key ID, and nothing private is
// ever exported.
func ExportPEM(pub minisign.PublicKey) ([]byte, error) {
raw := Ed25519Key(pub)
if raw == nil {
return nil, errors.New("not an Ed25519 minisign public key")
}
der, err := x509.MarshalPKIXPublicKey(raw)
if err != nil {
return nil, err
}
return pem.EncodeToMemory(&pem.Block{Type: "PUBLIC KEY", Bytes: der}), nil
}
// ImportPEM reads a PEM "PUBLIC KEY" block holding an Ed25519 key
// (e.g. a cosign.pub made from an Ed25519 key, or ExportPEM's output)
// and returns it as a minisign public key, so it can be pinned and
// trusted like any other (known-keys add, trust policy allow).
//
// PEM carries no key ID, so one is chosen: knownID's answer if it
// returns one for this key (a key this host already knows, e.g. one
// exported earlier, gets its old ID back), otherwise one derived from
// the key (the first 8 bytes of its SHA-256). Either way trust decisions
// compare the key itself, never the ID (see SameKey).
func ImportPEM(data []byte, knownID func(ed25519.PublicKey) (KeyID, bool)) (minisign.PublicKey, error) {
block, _ := pem.Decode(data)
if block == nil {
return minisign.PublicKey{}, errors.New("no PEM block found")
}
if block.Type != "PUBLIC KEY" {
return minisign.PublicKey{}, fmt.Errorf("PEM block is %q, want \"PUBLIC KEY\" (never import a private key)", block.Type)
}
parsed, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
return minisign.PublicKey{}, fmt.Errorf("parse public key: %w", err)
}
raw, ok := parsed.(ed25519.PublicKey)
if !ok {
return minisign.PublicKey{}, fmt.Errorf("unsupported key type %T: only Ed25519 keys can be imported (cosign generate-key-pair makes ECDSA P-256 keys)", parsed)
}
var id uint64
if knownID != nil {
if known, ok := knownID(raw); ok {
v, err := ParseKeyID(string(known))
if err == nil {
id = parseUint(v)
}
}
}
if id == 0 {
sum := sha256.Sum256(raw)
id = binary.LittleEndian.Uint64(sum[:8])
}
return minisignKey(id, raw)
}
// minisignKey builds a minisign public key from an ID and a raw key.
func minisignKey(id uint64, raw ed25519.PublicKey) (minisign.PublicKey, error) {
buf := make([]byte, 0, 2+8+ed25519.PublicKeySize)
buf = append(buf, 'E', 'd')
buf = binary.LittleEndian.AppendUint64(buf, id)
buf = append(buf, raw...)
return ParseKeyText(base64.StdEncoding.EncodeToString(buf))
}
func parseUint(id KeyID) uint64 {
v, _ := strconv.ParseUint(string(id), 16, 64)
return v
}
+32
View File
@@ -0,0 +1,32 @@
package trust
import (
"context"
"fmt"
"yetano.dev/yetano/core/secretref"
)
// KeyFromRef loads a signing key pair from a secret reference
// (secret://, env:, file:, base64: -- core/secretref), for example
// "secret://yabar/evidence/minisign" in yaseva. The value is a minisign
// private key file's contents. passwordRef ("" for none) is the
// reference of the password of an encrypted key. Error messages never
// contain the secret.
func KeyFromRef(ctx context.Context, r *secretref.Resolver, keyRef, passwordRef string) (KeyPair, error) {
data, err := r.Resolve(ctx, keyRef)
if err != nil {
return KeyPair{}, fmt.Errorf("signing key %s: %s", keyRef, r.Redact(err.Error()))
}
var password string
if passwordRef != "" {
if password, err = r.ResolveString(ctx, passwordRef); err != nil {
return KeyPair{}, fmt.Errorf("signing key password %s: %s", passwordRef, r.Redact(err.Error()))
}
}
kp, err := ParsePrivateKey(data, password)
if err != nil {
return KeyPair{}, fmt.Errorf("signing key %s: %s", keyRef, r.Redact(err.Error()))
}
return kp, nil
}
+64
View File
@@ -0,0 +1,64 @@
package trust
import (
"errors"
"fmt"
"strings"
"time"
"aead.dev/minisign"
)
// SignDigest makes the publisher signature of an OCI manifest digest:
// the Signature payload yet pushes as a referrer and VerifySignature
// checks. The trusted comment is "yet package digest: <digest>" (the
// format yet has always written).
func SignDigest(kp KeyPair, digest string) (Signature, error) {
trustedComment := "yet package digest: " + digest
sig := minisign.SignWithComments(kp.Private, []byte(digest), trustedComment, "")
pubText, err := kp.Public.MarshalText()
if err != nil {
return Signature{}, err
}
return Signature{
SchemaVersion: 1,
Algorithm: "minisign",
PublicKey: string(pubText),
Digest: digest,
Value: string(sig),
SignedAt: time.Now().UTC(),
}, nil
}
// Sign makes a detached minisign signature of message: the text of a
// ".minisig" file, which "minisign -V -m <file>" verifies against the
// key's ".pub" file. trustedComment is signed with it (one line);
// untrustedComment is not ("" for minisign's default).
func Sign(kp KeyPair, message []byte, trustedComment, untrustedComment string) ([]byte, error) {
if strings.ContainsAny(trustedComment, "\r\n") || strings.ContainsAny(untrustedComment, "\r\n") {
return nil, errors.New("a minisign comment is one line")
}
return minisign.SignWithComments(kp.Private, message, trustedComment, untrustedComment), nil
}
// ErrBadSignature: a signature does not verify (wrong key, changed
// message or changed trusted comment).
var ErrBadSignature = errors.New("signature does not verify")
// VerifyMessage checks a detached minisign signature (Sign's output, or
// a ".minisig" file from the minisign tool) of message against pub and
// returns its trusted comment, which the signature covers. A signature
// by another key fails, also when its key ID collides with pub's.
func VerifyMessage(pub minisign.PublicKey, message, signature []byte) (trustedComment string, err error) {
var sig minisign.Signature
if err := sig.UnmarshalText(signature); err != nil {
return "", fmt.Errorf("parse signature: %w", err)
}
if sig.KeyID != pub.ID() {
return "", fmt.Errorf("%w: signed by key %s, not %s", ErrBadSignature, KeyIDFromUint(sig.KeyID), ID(pub))
}
if !minisign.Verify(pub, message, signature) {
return "", ErrBadSignature
}
return sig.TrustedComment, nil
}
+165
View File
@@ -0,0 +1,165 @@
package trust
import (
"bytes"
"context"
"encoding/base64"
"errors"
"os"
"path/filepath"
"strings"
"testing"
"aead.dev/minisign"
"yetano.dev/yetano/core/secretref"
)
func vectorKey(t *testing.T) KeyPair {
t.Helper()
kp, err := LoadPrivateKey("testdata/sign-vector.key", "")
if err != nil {
t.Fatal(err)
}
return kp
}
// The golden vector: a fixed key and message give exactly the committed
// .minisig (Ed25519 is deterministic), and it verifies with the .pub.
// "minisign -Vm testdata/sign-vector.msg -p testdata/sign-vector.pub"
// verifies it as well.
func TestSignVector(t *testing.T) {
kp := vectorKey(t)
msg, _ := os.ReadFile("testdata/sign-vector.msg")
want, _ := os.ReadFile("testdata/sign-vector.msg.minisig")
got, err := Sign(kp, msg, "yabar evidence test-vector 00000000000000000000000000000000", "")
if err != nil || !bytes.Equal(got, want) {
t.Fatalf("signature differs from the vector (%v):\n%s", err, got)
}
pub, err := LoadPublicKey("testdata/sign-vector.pub")
if err != nil || !SameKey(pub, kp.Public) {
t.Fatalf("public key: %v", err)
}
tc, err := VerifyMessage(pub, msg, want)
if err != nil || tc != "yabar evidence test-vector 00000000000000000000000000000000" {
t.Fatalf("verify: %q %v", tc, err)
}
}
func TestVerifyMessageRejects(t *testing.T) {
kp := vectorKey(t)
msg := []byte("evidence")
sig, _ := Sign(kp, msg, "trusted", "untrusted")
if _, err := VerifyMessage(kp.Public, []byte("evidencE"), sig); !errors.Is(err, ErrBadSignature) {
t.Fatalf("changed message: %v", err)
}
changed := bytes.Replace(sig, []byte("trusted comment: trusted"), []byte("trusted comment: trustee"), 1)
if _, err := VerifyMessage(kp.Public, msg, changed); !errors.Is(err, ErrBadSignature) {
t.Fatalf("changed trusted comment: %v", err)
}
// The untrusted comment is not covered.
free := bytes.Replace(sig, []byte("untrusted comment: untrusted"), []byte("untrusted comment: whatever"), 1)
if _, err := VerifyMessage(kp.Public, msg, free); err != nil {
t.Fatalf("untrusted comment: %v", err)
}
other, _ := GenerateKey()
if _, err := VerifyMessage(other.Public, msg, sig); !errors.Is(err, ErrBadSignature) {
t.Fatalf("other key: %v", err)
}
if _, err := VerifyMessage(kp.Public, msg, []byte("garbage")); err == nil {
t.Fatal("garbage verified")
}
if _, err := Sign(kp, msg, "two\nlines", ""); err == nil {
t.Fatal("a two-line comment was accepted")
}
}
// What SignDigest makes, VerifySignature (the verifying half every
// consumer uses) accepts, and only for that digest.
func TestSignDigestVerifies(t *testing.T) {
kp := vectorKey(t)
const d = "sha256:2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae"
sig, err := SignDigest(kp, d)
if err != nil {
t.Fatal(err)
}
if v := VerifySignature(d, sig); !v.Valid || v.KeyID != ID(kp.Public) {
t.Fatalf("verify: %+v", v)
}
if v := VerifySignature("sha256:"+strings.Repeat("0", 64), sig); v.Valid {
t.Fatal("verified for another digest")
}
tc, err := VerifyMessage(kp.Public, []byte(d), []byte(sig.Value))
if err != nil || tc != "yet package digest: "+d {
t.Fatalf("trusted comment %q %v", tc, err)
}
}
func TestKeyFiles(t *testing.T) {
dir := t.TempDir()
kp, _ := GenerateKey()
for _, pw := range []string{"", "secret"} {
p := filepath.Join(dir, "k"+pw)
if err := SaveKeyPair(p, kp, pw); err != nil {
t.Fatal(err)
}
got, err := LoadPrivateKey(p, pw)
if err != nil || !SameKey(got.Public, kp.Public) {
t.Fatalf("password %q: %v", pw, err)
}
pub, err := LoadPublicKey(p + ".pub")
if err != nil || !SameKey(pub, kp.Public) {
t.Fatalf(".pub: %v", err)
}
if fi, _ := os.Stat(p); os.PathSeparator == '/' && fi.Mode().Perm() != 0o600 {
t.Fatalf("private key mode %v", fi.Mode())
}
}
if _, err := LoadPrivateKey(filepath.Join(dir, "ksecret"), "wrong"); err == nil {
t.Fatal("wrong password accepted")
}
b, _ := MarshalPublicKey(kp.Public)
if !bytes.HasPrefix(b, []byte("untrusted comment: minisign public key: "+string(ID(kp.Public))+"\n")) {
t.Fatalf("public key file: %s", b)
}
}
func TestEd25519AndPEM(t *testing.T) {
kp := vectorKey(t)
sig, err := SignEd25519(kp, []byte("statement"))
if err != nil || !VerifyEd25519(kp.Public, []byte("statement"), sig) || VerifyEd25519(kp.Public, []byte("statemenT"), sig) {
t.Fatalf("ed25519: %v", err)
}
p, err := ExportPEM(kp.Public)
if err != nil {
t.Fatal(err)
}
back, err := ImportPEM(p, nil)
if err != nil || !SameKey(back, kp.Public) {
t.Fatalf("PEM round trip: %v", err)
}
}
func TestKeyFromRef(t *testing.T) {
kp := vectorKey(t)
priv, _ := os.ReadFile("testdata/sign-vector.key")
r := secretref.New("")
got, err := KeyFromRef(context.Background(), r, "base64:"+base64.StdEncoding.EncodeToString(priv), "")
if err != nil || !SameKey(got.Public, kp.Public) {
t.Fatalf("base64 ref: %v", err)
}
enc, _ := minisign.EncryptKey("pw", kp.Private)
t.Setenv("TRUST_TEST_KEY", string(enc))
t.Setenv("TRUST_TEST_PW", "pw")
if got, err = KeyFromRef(context.Background(), r, "env:TRUST_TEST_KEY", "env:TRUST_TEST_PW"); err != nil || !SameKey(got.Public, kp.Public) {
t.Fatalf("encrypted env ref: %v", err)
}
t.Setenv("TRUST_TEST_PW", "wrong-password")
_, err = KeyFromRef(context.Background(), secretref.New(""), "env:TRUST_TEST_KEY", "env:TRUST_TEST_PW")
if err == nil || strings.Contains(err.Error(), "wrong-password") {
t.Fatalf("wrong password: %v", err)
}
if _, err := KeyFromRef(context.Background(), r, "not a reference", ""); err == nil {
t.Fatal("plaintext accepted")
}
}
+2
View File
@@ -0,0 +1,2 @@
untrusted comment: minisign encrypted secret key
RWQAAEIyAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMIu3pReIO0jw8qjsUD5/2J9b2y+5BNJ45wLRkzgleRSUugHITToa6mGDGFfLcgDIs+wEX4vFIUfnrLqym+u2yLqBzAYgET+YAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA=
+1
View File
@@ -0,0 +1 @@
yabar evidence vector
+4
View File
@@ -0,0 +1,4 @@
untrusted comment:
RWQwi7elF4g7SHc9svLZOCFGGEyXs7gZW6saVrYobxgEdJnDM9hIxHIlC+qxicazJFYu2E6TG3Qq62NTae3k0rDlomfkxxz8oQA=
trusted comment: yabar evidence test-vector 00000000000000000000000000000000
o0/jQwycdwDK6BrI5jc6N47P2ixexYe07twyQ587cJBWapfKNch5EmMgvvwR6thKci3Lg0dpuanBDFdVP9QcCw==
+2
View File
@@ -0,0 +1,2 @@
untrusted comment: minisign public key: 483B8817A5B78B30
RWQwi7elF4g7SGGDGFfLcgDIs+wEX4vFIUfnrLqym+u2yLqBzAYgET+Y