Compare commits

...
Author SHA1 Message Date
sam 6b4ff8101a fix(governance): ask for the public URL during owner setup (#2076) 2026-11-27 02:33:15 +11:00
11 changed files with 147 additions and 147 deletions

No files matched your search

+19 -7
View File
@@ -2756,16 +2756,10 @@ components:
type: string
email:
type: string
organisation_name:
type: string
password:
type: string
public_url:
type: string
role:
type: string
workspace_name:
type: string
required:
- email
- display_name
@@ -4672,6 +4666,24 @@ components:
required:
- role
type: object
SetUpInputBody:
additionalProperties: false
properties:
display_name:
type: string
email:
type: string
password:
type: string
public_url:
description: The public origin of this Archie instance
type: string
required:
- public_url
- email
- display_name
- password
type: object
SignInInputBody:
additionalProperties: false
properties:
@@ -5690,7 +5702,7 @@ paths:
content:
application/json:
schema:
$ref: "#/components/schemas/GovernanceRegistration"
$ref: "#/components/schemas/SetUpInputBody"
required: true
responses:
"200":
+1 -1
View File
@@ -17,7 +17,7 @@ module.exports = async ({ page, go, shot, settled, tolerate }) => {
await page.keyboard.press('Escape');
return names;
})();
assert.deepEqual(offered.sort(), ['Beta', 'E2E'], 'selector must offer exactly the orgs the caller belongs to');
assert.deepEqual(offered.sort(), ['Beta', 'System'], 'selector must offer exactly the orgs the caller belongs to');
await go('/workflows');
await page.getByText('Parked', { exact: true }).first().waitFor();
await shot('home-org-workflows');
+1 -1
View File
@@ -18,7 +18,7 @@ py() { python3 -c "import sys, json; d = json.load(sys.stdin); print($1)"; }
# This account belongs only to the isolated local test stack.
email=${ARCHIE_E2E_EMAIL:-operator@example.test}
password=${ARCHIE_E2E_PASSWORD:-archie-local-e2e-password}
account=$(python3 -c 'import json,sys; print(json.dumps(dict(email=sys.argv[1], password=sys.argv[2], display_name="E2E operator", organisation_name="E2E", workspace_name="Local test", public_url=sys.argv[3])))' "$email" "$password" "${ARCHIE_E2E_URL:-http://localhost:5173}")
account=$(python3 -c 'import json,sys; print(json.dumps(dict(email=sys.argv[1], password=sys.argv[2], display_name="E2E operator", public_url=sys.argv[3])))' "$email" "$password" "${ARCHIE_E2E_URL:-http://localhost:5173}")
if [ "$(get /api/auth/status | py 'd["setup_required"]')" = "True" ]; then
post /api/auth/setup "$account" >/dev/null
else
+3 -30
View File
@@ -6,7 +6,6 @@ import (
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"strings"
"time"
@@ -75,7 +74,7 @@ func writeAccount(ctx context.Context, tx pgx.Tx, r identity.AccountRegistration
now := time.Now().UTC()
value.CreatedAt, value.UpdatedAt = now, now
if bootstrap {
if err := setupAccountOrganisation(ctx, tx, r, orgID, now); err != nil {
if _, err := tx.Exec(ctx, `INSERT INTO authentication_settings (public_url) VALUES ($1)`, r.PublicURL); err != nil {
return identity.Identity{}, err
}
}
@@ -229,7 +228,8 @@ func accountRegistrationScope(ctx context.Context, r *identity.AccountRegistrati
role := org.Role(r.Role)
orgID := org.OrgFromContext(ctx)
if bootstrap {
if err := validateAccountSetup(r); err != nil {
r.PublicURL = strings.TrimRight(strings.TrimSpace(r.PublicURL), "/")
if err := (identity.AuthenticationSettings{PublicURL: r.PublicURL}).Validate(); err != nil {
return "", "", err
}
return org.RoleOwner, org.DefaultOrgID, nil
@@ -257,30 +257,3 @@ func recordFailedAccountLogin(ctx context.Context, tx pgx.Tx, id string, attempt
}
return identity.ErrCredentialRejected
}
func setupAccountOrganisation(ctx context.Context, tx pgx.Tx, r identity.AccountRegistration, orgID org.OrgID, now time.Time) error {
_, err := tx.Exec(ctx, `UPDATE orgs SET name=$1, updated_at=$2 WHERE id=$3`, r.OrganisationName, now, string(orgID))
if err != nil {
return err
}
if _, err := tx.Exec(ctx, `UPDATE workspaces SET name=$1,updated_at=$2 WHERE org_id=$3 AND id=$4`, r.WorkspaceName, now, string(orgID), string(org.DefaultWorkspaceID)); err != nil {
return err
}
if _, err := tx.Exec(ctx, `INSERT INTO authentication_settings (public_url) VALUES ($1)`, r.PublicURL); err != nil {
return err
}
return nil
}
func validateAccountSetup(r *identity.AccountRegistration) error {
r.OrganisationName = strings.TrimSpace(r.OrganisationName)
r.WorkspaceName = strings.TrimSpace(r.WorkspaceName)
r.PublicURL = strings.TrimRight(r.PublicURL, "/")
if r.WorkspaceName == "" || len(r.WorkspaceName) > 200 {
return identity.ErrInvalid
}
if r.OrganisationName == "" || len(r.OrganisationName) > 200 {
return fmt.Errorf("%w: organisation name is required", identity.ErrInvalid)
}
return (identity.AuthenticationSettings{PublicURL: r.PublicURL}).Validate()
}
@@ -0,0 +1,10 @@
-- +goose Up
INSERT INTO governance.orgs (id, name) VALUES ('org-sys', 'System')
ON CONFLICT (id) DO NOTHING;
INSERT INTO governance.workspaces (id, org_id, name) VALUES ('default', 'org-sys', 'Default')
ON CONFLICT (org_id, id) DO NOTHING;
-- +goose Down
-- The built-in rows may own user data. Keep them on downgrade.
SELECT 1;
+13 -10
View File
@@ -193,26 +193,29 @@ func (m *Module) authStatus(ctx context.Context, in *sessionInput) (*authStatusR
}
type registration struct {
PublicURL string `json:"public_url,omitempty"`
WorkspaceName string `json:"workspace_name,omitempty"`
OrganisationName string `json:"organisation_name,omitempty"`
Email string `json:"email"`
DisplayName string `json:"display_name"`
Password string `json:"password"`
Role string `json:"role,omitempty"`
Email string `json:"email"`
DisplayName string `json:"display_name"`
Password string `json:"password"`
Role string `json:"role,omitempty"`
}
func (r registration) account() AccountRegistration {
return AccountRegistration(r)
return AccountRegistration{Email: r.Email, DisplayName: r.DisplayName, Password: r.Password, Role: r.Role}
}
type setUpInput struct {
Client client
Body registration
Body struct {
PublicURL string `json:"public_url" doc:"The public origin of this Archie instance"`
Email string `json:"email"`
DisplayName string `json:"display_name"`
Password string `json:"password"`
}
}
func (m *Module) setUpAccount(ctx context.Context, in *setUpInput) (*userReply, error) {
if _, err := m.RegisterAccount(ctx, in.Body.account(), true); err != nil {
r := in.Body
if _, err := m.RegisterAccount(ctx, AccountRegistration{PublicURL: r.PublicURL, Email: r.Email, DisplayName: r.DisplayName, Password: r.Password}, true); err != nil {
return nil, m.accountError(ctx, err)
}
return m.openSession(ctx, &in.Client, in.Body.Email, in.Body.Password)
+27
View File
@@ -0,0 +1,27 @@
package governance
import (
"errors"
"testing"
)
// TestBootstrapRequiresThePublicOrigin guards the WebAuthn origin without requiring names for built-in rows.
func TestBootstrapRequiresThePublicOrigin(t *testing.T) {
for _, tc := range []struct {
url string
wantErr error
}{
{"https://archie.example.test/", nil},
{"", ErrInvalidIdentity},
{"https://archie.example.test/some/path", ErrInvalidIdentity},
} {
r := AccountRegistration{PublicURL: tc.url, Email: "owner@example.test", DisplayName: "Owner"}
role, org, err := registrationScope(t.Context(), &r, true)
if !errors.Is(err, tc.wantErr) {
t.Errorf("register with origin %q: %v, want %v", tc.url, err, tc.wantErr)
}
if err == nil && (r.PublicURL != "https://archie.example.test" || role != RoleOwner || org != DefaultOrgID) {
t.Errorf("bootstrap scope = %s/%s, origin = %q", org, role, r.PublicURL)
}
}
}
+5 -7
View File
@@ -387,13 +387,11 @@ const AccountSessionLifetime = 7 * 24 * time.Hour
// AccountRegistration carries the fields needed to register an account or
// bootstrap the instance owner.
type AccountRegistration struct {
PublicURL string `json:"public_url"`
WorkspaceName string `json:"workspace_name"`
OrganisationName string `json:"organisation_name"`
Email string `json:"email"`
DisplayName string `json:"display_name"`
Password string `json:"password"`
Role string `json:"role"`
PublicURL string `json:"public_url"`
Email string `json:"email"`
DisplayName string `json:"display_name"`
Password string `json:"password"`
Role string `json:"role"`
}
// Validate normalises email and display name and checks their bounds.
+14 -29
View File
@@ -35,20 +35,17 @@ type AuthSettingsRow struct {
// RegisterAccountParams carries the validated inputs to create a user account.
type RegisterAccountParams struct {
IdentityID string
Email string
DisplayName string
PasswordHash string
OrgID string
OrgName string
WorkspaceID string
WorkspaceName string
PublicURL string
Role string
ActorID string
RequestID string
Bootstrap bool
Now time.Time
IdentityID string
Email string
DisplayName string
PasswordHash string
OrgID string
PublicURL string
Role string
ActorID string
RequestID string
Bootstrap bool
Now time.Time
}
// AccountSetupRequired reports whether no local accounts exist yet.
@@ -76,7 +73,7 @@ func (s *Store) RegisterAccount(ctx context.Context, p RegisterAccountParams) (I
return ErrCredentialRejected
}
if p.Bootstrap {
if err := bootstrapOrgAndSettings(ctx, tx, p); err != nil {
if err := saveBootstrapOrigin(ctx, tx, p.PublicURL); err != nil {
return err
}
}
@@ -85,22 +82,10 @@ func (s *Store) RegisterAccount(ctx context.Context, p RegisterAccountParams) (I
return out, err
}
func bootstrapOrgAndSettings(ctx context.Context, tx *sqlx.Tx, p RegisterAccountParams) error {
if _, err := tx.ExecContext(ctx, `
INSERT INTO governance.orgs (id, name, created_at, updated_at) VALUES ($1, $2, $3, $3)
ON CONFLICT (id) DO UPDATE SET name = EXCLUDED.name, updated_at = EXCLUDED.updated_at`,
p.OrgID, p.OrgName, p.Now); err != nil {
return err
}
if _, err := tx.ExecContext(ctx, `
INSERT INTO governance.workspaces (id, org_id, name, created_at, updated_at) VALUES ($1, $2, $3, $4, $4)
ON CONFLICT (org_id, id) DO UPDATE SET name = EXCLUDED.name, updated_at = EXCLUDED.updated_at`,
p.WorkspaceID, p.OrgID, p.WorkspaceName, p.Now); err != nil {
return err
}
func saveBootstrapOrigin(ctx context.Context, tx *sqlx.Tx, origin string) error {
_, err := tx.ExecContext(ctx, `
INSERT INTO governance.authentication_settings (singleton, public_url) VALUES (true, $1)
ON CONFLICT (singleton) DO UPDATE SET public_url = EXCLUDED.public_url`, p.PublicURL)
ON CONFLICT (singleton) DO UPDATE SET public_url = EXCLUDED.public_url`, origin)
return err
}
+2 -8
View File
@@ -386,8 +386,7 @@ func (m *Module) RegisterAccount(ctx context.Context, r AccountRegistration, boo
}
row, err := m.store.RegisterAccount(ctx, store.RegisterAccountParams{
IdentityID: string(id), Email: r.Email, DisplayName: r.DisplayName,
PasswordHash: hash, OrgID: string(orgID), OrgName: r.OrganisationName,
WorkspaceID: string(DefaultWorkspaceID), WorkspaceName: r.WorkspaceName,
PasswordHash: hash, OrgID: string(orgID),
PublicURL: r.PublicURL, Role: string(role), ActorID: string(actor),
RequestID: "account:" + rand.Text(), Bootstrap: bootstrap, Now: time.Now().UTC(),
})
@@ -408,12 +407,7 @@ func registrationScope(ctx context.Context, r *AccountRegistration, bootstrap bo
return "", "", err
}
if bootstrap {
r.OrganisationName = strings.TrimSpace(r.OrganisationName)
r.WorkspaceName = strings.TrimSpace(r.WorkspaceName)
r.PublicURL = strings.TrimRight(r.PublicURL, "/")
if r.WorkspaceName == "" || len(r.WorkspaceName) > 200 || r.OrganisationName == "" || len(r.OrganisationName) > 200 {
return "", "", ErrInvalidIdentity
}
r.PublicURL = strings.TrimRight(strings.TrimSpace(r.PublicURL), "/")
if err := (AuthenticationSettings{PublicURL: r.PublicURL}).Validate(); err != nil {
return "", "", err
}
+52 -54
View File
@@ -6,38 +6,34 @@ import { computed, ref } from "vue";
import { Card } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { api, describeError } from "@/lib/api";
import { api, ApiError, describeError } from "@/lib/api";
import { errors } from "@/copy/errors";
import { passkeysAvailable, useAccountsStore, usePasskey } from "./accounts";
const accounts = useAccountsStore();
const recovery = ref(false);
const recoveryCode = ref("");
const organisation = ref("");
const workspace = ref("Default");
const publicURL = ref("");
const currentOrigin = window.location.origin;
const name = ref("");
const email = ref("");
const password = ref("");
const busy = ref(false);
const error = ref("");
const notice = ref("");
const ownerCreated = ref(false);
const setup = computed(() => accounts.status?.setup_required === true);
const passkey = computed(() => passkeysAvailable(accounts.status?.public_url ?? ""));
// Setup asks one thing at a time: the organisation, then its first workspace,
// then the account that owns it.
const ACCOUNT_STEP = 3;
const step = ref(1);
async function submit() {
if (setup.value && !recovery.value && step.value < ACCOUNT_STEP) {
step.value += 1;
return;
}
busy.value = true;
error.value = "";
notice.value = "";
try {
if (ownerCreated.value) {
await openAccountWhenReady();
return;
}
if (recovery.value) {
await api.recoverAccount(email.value, recoveryCode.value, password.value);
recovery.value = false;
@@ -46,35 +42,46 @@ async function submit() {
return;
}
if (setup.value) {
// The instance URL is the address the operator already reached, and it
// stays editable under Settings, authentication once passkeys exist.
await api.setupAccount({
organisation_name: organisation.value,
workspace_name: workspace.value,
public_url: window.location.origin,
public_url: publicURL.value.trim(),
display_name: name.value,
email: email.value,
password: password.value,
});
} else {
await api.signIn(email.value, password.value);
password.value = "";
ownerCreated.value = true;
await openAccountWhenReady();
return;
}
await api.signIn(email.value, password.value);
password.value = "";
window.location.assign(
setup.value
? "/account?welcome=1"
: new URLSearchParams(window.location.search).has("reauth")
? "/account"
: "/",
);
window.location.assign(new URLSearchParams(window.location.search).has("reauth") ? "/account" : "/");
} catch (cause) {
error.value = describeError(cause, errors.common.unknown);
await accounts.load();
if (!ownerCreated.value) await accounts.load();
} finally {
busy.value = false;
}
}
async function openAccountWhenReady(): Promise<void> {
const deadline = Date.now() + 15_000;
// Setup creates the owner before Archie opens its operational routes.
for (;;) {
try {
await api.passkeys();
window.location.assign("/account?welcome=1");
return;
} catch (cause) {
if (!(cause instanceof ApiError) || cause.status !== 404) throw cause;
if (Date.now() >= deadline) {
throw new Error("Archie hasn't finished starting. Try opening your account again.");
}
await new Promise((resolve) => window.setTimeout(resolve, 500));
}
}
}
async function signInPasskey() {
busy.value = true;
error.value = "";
@@ -95,37 +102,28 @@ async function signInPasskey() {
<div class="mb-2"><Logo /></div>
<h1 class="text-title font-medium">
{{
setup
? step === 1
? "Set up your organisation"
: step === 2
? "Create your first workspace"
: "Create your account"
: recovery
? "Recover your account"
: "Sign in"
setup ? "Set up Archie" : recovery ? "Recover your account" : "Sign in"
}}
</h1>
<form class="mt-6 space-y-4" @submit.prevent="submit">
<template v-if="setup && step === 1">
<Label class="block space-y-1.5 text-label" for="organisation">Name<Input id="organisation" v-model="organisation" autocomplete="organization" required maxlength="200" /></Label>
</template>
<template v-else-if="setup && step === 2">
<Label class="block space-y-1.5 text-label" for="workspace">Name<Input id="workspace" v-model="workspace" required maxlength="200" /></Label>
</template>
<template v-else>
<Label v-if="setup" class="block space-y-1.5 text-label" for="account-name">Your name<Input id="account-name" v-model="name" autocomplete="name" required maxlength="200" /></Label>
<Label class="block space-y-1.5 text-label" for="account-email">Email<Input id="account-email" v-model="email" type="email" autocomplete="username" :spellcheck="false" required /></Label>
<Label v-if="recovery" class="block space-y-1.5 text-label" for="recovery-code">Recovery code<Input id="recovery-code" v-model="recoveryCode" autocomplete="off" required /></Label>
<Label class="block space-y-1.5 text-label" for="account-password">{{ recovery ? "New password" : "Password" }}<Input id="account-password" v-model="password" type="password" :autocomplete="setup || recovery ? 'new-password' : 'current-password'" :minlength="setup || recovery ? 15 : undefined" maxlength="1024" required /></Label>
<p v-if="setup" class="text-caption text-fg-muted">At least 15 characters.</p>
</template>
<div v-if="ownerCreated" class="mt-6 space-y-4">
<p role="status">Your account is ready. Archie is starting.</p>
<Alert v-if="error" variant="destructive"><AlertDescription>{{ error }}</AlertDescription></Alert>
<Button v-if="!busy" class="w-full" @click="submit">Open your account</Button>
</div>
<form v-else class="mt-6 space-y-4" @submit.prevent="submit">
<div v-if="setup" class="flex flex-col gap-1.5">
<Label for="instance-url">Instance URL</Label>
<Input id="instance-url" v-model="publicURL" type="url" :placeholder="currentOrigin" aria-describedby="instance-url-help" required />
<p id="instance-url-help" class="text-caption text-fg-muted">Use the public address people will sign in at. You can't change it after adding a passkey.</p>
</div>
<Label v-if="setup" class="block space-y-1.5 text-label" for="account-name">Your name<Input id="account-name" v-model="name" autocomplete="name" required maxlength="200" /></Label>
<Label class="block space-y-1.5 text-label" for="account-email">Email<Input id="account-email" v-model="email" type="email" autocomplete="username" :spellcheck="false" required /></Label>
<Label v-if="recovery" class="block space-y-1.5 text-label" for="recovery-code">Recovery code<Input id="recovery-code" v-model="recoveryCode" autocomplete="off" required /></Label>
<Label class="block space-y-1.5 text-label" for="account-password">{{ recovery ? "New password" : "Password" }}<Input id="account-password" v-model="password" type="password" :autocomplete="setup || recovery ? 'new-password' : 'current-password'" :minlength="setup || recovery ? 15 : undefined" maxlength="1024" required /></Label>
<p v-if="setup" class="text-caption text-fg-muted">At least 15 characters.</p>
<Alert v-if="error" variant="destructive"><AlertDescription>{{ error }}</AlertDescription></Alert>
<Alert v-if="notice" class="mt-4"><AlertDescription>{{ notice }}</AlertDescription></Alert>
<div class="flex gap-2">
<Button v-if="setup && step > 1" type="button" variant="outline" :disabled="busy" @click="step -= 1">Back</Button>
<Button type="submit" class="flex-1" :disabled="busy">{{ busy ? "Please wait…" : setup ? (step === ACCOUNT_STEP ? "Create account" : "Continue") : recovery ? "Reset password" : "Sign in" }}</Button>
</div>
<Button type="submit" class="w-full" :disabled="busy">{{ busy ? "Please wait…" : setup ? "Create account" : recovery ? "Reset password" : "Sign in" }}</Button>
</form>
<div v-if="!setup && !recovery" class="mt-4 flex flex-col gap-2">
<Button v-if="passkey" variant="outline" :disabled="busy" @click="signInPasskey">Sign in with a passkey</Button>