var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
    function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
    var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
    var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
    var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
    var _, done = false;
    for (var i = decorators.length - 1; i >= 0; i--) {
        var context = {};
        for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
        for (var p in contextIn.access) context.access[p] = contextIn.access[p];
        context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
        var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
        if (kind === "accessor") {
            if (result === void 0) continue;
            if (result === null || typeof result !== "object") throw new TypeError("Object expected");
            if (_ = accept(result.get)) descriptor.get = _;
            if (_ = accept(result.set)) descriptor.set = _;
            if (_ = accept(result.init)) initializers.unshift(_);
        }
        else if (_ = accept(result)) {
            if (kind === "field") initializers.unshift(_);
            else descriptor[key] = _;
        }
    }
    if (target) Object.defineProperty(target, contextIn.name, descriptor);
    done = true;
};
var __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) {
    var useValue = arguments.length > 2;
    for (var i = 0; i < initializers.length; i++) {
        value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
    }
    return useValue ? value : void 0;
};
import * as plugins from '../plugins.js';
import * as interfaces from '../../dist_ts_interfaces/index.js';
import { DeesElement, customElement, html, state, css, cssManager, } from '@design.estate/dees-element';
let ObAuthGate = (() => {
    let _classDecorators = [customElement('ob-auth-gate')];
    let _classDescriptor;
    let _classExtraInitializers = [];
    let _classThis;
    let _classSuper = DeesElement;
    let _authState_decorators;
    let _authState_initializers = [];
    let _authState_extraInitializers = [];
    let _bootstrapCodeExpired_decorators;
    let _bootstrapCodeExpired_initializers = [];
    let _bootstrapCodeExpired_extraInitializers = [];
    let _bootstrapToken_decorators;
    let _bootstrapToken_initializers = [];
    let _bootstrapToken_extraInitializers = [];
    let _message_decorators;
    let _message_initializers = [];
    let _message_extraInitializers = [];
    let _errorMessage_decorators;
    let _errorMessage_initializers = [];
    let _errorMessage_extraInitializers = [];
    let _busy_decorators;
    let _busy_initializers = [];
    let _busy_extraInitializers = [];
    var ObAuthGate = class extends _classSuper {
        static { _classThis = this; }
        static {
            const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
            _authState_decorators = [state()];
            _bootstrapCodeExpired_decorators = [state()];
            _bootstrapToken_decorators = [state()];
            _message_decorators = [state()];
            _errorMessage_decorators = [state()];
            _busy_decorators = [state()];
            __esDecorate(this, null, _authState_decorators, { kind: "accessor", name: "authState", static: false, private: false, access: { has: obj => "authState" in obj, get: obj => obj.authState, set: (obj, value) => { obj.authState = value; } }, metadata: _metadata }, _authState_initializers, _authState_extraInitializers);
            __esDecorate(this, null, _bootstrapCodeExpired_decorators, { kind: "accessor", name: "bootstrapCodeExpired", static: false, private: false, access: { has: obj => "bootstrapCodeExpired" in obj, get: obj => obj.bootstrapCodeExpired, set: (obj, value) => { obj.bootstrapCodeExpired = value; } }, metadata: _metadata }, _bootstrapCodeExpired_initializers, _bootstrapCodeExpired_extraInitializers);
            __esDecorate(this, null, _bootstrapToken_decorators, { kind: "accessor", name: "bootstrapToken", static: false, private: false, access: { has: obj => "bootstrapToken" in obj, get: obj => obj.bootstrapToken, set: (obj, value) => { obj.bootstrapToken = value; } }, metadata: _metadata }, _bootstrapToken_initializers, _bootstrapToken_extraInitializers);
            __esDecorate(this, null, _message_decorators, { kind: "accessor", name: "message", static: false, private: false, access: { has: obj => "message" in obj, get: obj => obj.message, set: (obj, value) => { obj.message = value; } }, metadata: _metadata }, _message_initializers, _message_extraInitializers);
            __esDecorate(this, null, _errorMessage_decorators, { kind: "accessor", name: "errorMessage", static: false, private: false, access: { has: obj => "errorMessage" in obj, get: obj => obj.errorMessage, set: (obj, value) => { obj.errorMessage = value; } }, metadata: _metadata }, _errorMessage_initializers, _errorMessage_extraInitializers);
            __esDecorate(this, null, _busy_decorators, { kind: "accessor", name: "busy", static: false, private: false, access: { has: obj => "busy" in obj, get: obj => obj.busy, set: (obj, value) => { obj.busy = value; } }, metadata: _metadata }, _busy_initializers, _busy_extraInitializers);
            __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name, metadata: _metadata }, null, _classExtraInitializers);
            ObAuthGate = _classThis = _classDescriptor.value;
            if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
        }
        #authState_accessor_storage = __runInitializers(this, _authState_initializers, 'loading');
        get authState() { return this.#authState_accessor_storage; }
        set authState(value) { this.#authState_accessor_storage = value; }
        #bootstrapCodeExpired_accessor_storage = (__runInitializers(this, _authState_extraInitializers), __runInitializers(this, _bootstrapCodeExpired_initializers, false));
        get bootstrapCodeExpired() { return this.#bootstrapCodeExpired_accessor_storage; }
        set bootstrapCodeExpired(value) { this.#bootstrapCodeExpired_accessor_storage = value; }
        #bootstrapToken_accessor_storage = (__runInitializers(this, _bootstrapCodeExpired_extraInitializers), __runInitializers(this, _bootstrapToken_initializers, ''));
        get bootstrapToken() { return this.#bootstrapToken_accessor_storage; }
        set bootstrapToken(value) { this.#bootstrapToken_accessor_storage = value; }
        #message_accessor_storage = (__runInitializers(this, _bootstrapToken_extraInitializers), __runInitializers(this, _message_initializers, ''));
        get message() { return this.#message_accessor_storage; }
        set message(value) { this.#message_accessor_storage = value; }
        #errorMessage_accessor_storage = (__runInitializers(this, _message_extraInitializers), __runInitializers(this, _errorMessage_initializers, ''));
        get errorMessage() { return this.#errorMessage_accessor_storage; }
        set errorMessage(value) { this.#errorMessage_accessor_storage = value; }
        #busy_accessor_storage = (__runInitializers(this, _errorMessage_extraInitializers), __runInitializers(this, _busy_initializers, false));
        get busy() { return this.#busy_accessor_storage; }
        set busy(value) { this.#busy_accessor_storage = value; }
        static styles = [
            cssManager.defaultStyles,
            css `
      :host {
        display: grid;
        min-height: 100vh;
        place-items: center;
        padding: 24px;
        color: #f7f8fb;
        background:
          radial-gradient(circle at 20% 20%, rgba(77, 114, 255, 0.2), transparent 38%),
          linear-gradient(145deg, #10141d, #080a0f);
        box-sizing: border-box;
      }

      :host([hidden]) {
        display: none;
      }

      .card {
        width: min(440px, 100%);
        padding: 34px;
        border: 1px solid rgba(255, 255, 255, 0.12);
        border-radius: 20px;
        background: rgba(19, 24, 35, 0.94);
        box-shadow: 0 24px 80px rgba(0, 0, 0, 0.42);
      }

      .eyebrow {
        margin-bottom: 10px;
        color: #8ea6ff;
        font-size: 12px;
        font-weight: 700;
        letter-spacing: 0.14em;
        text-transform: uppercase;
      }

      h1 {
        margin: 0;
        font-size: 30px;
        line-height: 1.15;
      }

      p {
        margin: 14px 0 0;
        color: #b9c0cf;
        line-height: 1.55;
      }

      label {
        display: block;
        margin-top: 24px;
        color: #dbe0ea;
        font-size: 13px;
        font-weight: 600;
      }

      input {
        width: 100%;
        margin-top: 8px;
        padding: 13px 14px;
        color: #fff;
        border: 1px solid rgba(255, 255, 255, 0.18);
        border-radius: 10px;
        outline: none;
        background: rgba(0, 0, 0, 0.28);
        font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
        box-sizing: border-box;
      }

      input:focus {
        border-color: #7893ff;
        box-shadow: 0 0 0 3px rgba(120, 147, 255, 0.15);
      }

      button {
        width: 100%;
        margin-top: 24px;
        padding: 13px 18px;
        color: #fff;
        border: 0;
        border-radius: 10px;
        background: #526fe8;
        cursor: pointer;
        font: inherit;
        font-weight: 700;
      }

      button:hover:not(:disabled) {
        background: #6480ee;
      }

      button:disabled {
        cursor: wait;
        opacity: 0.6;
      }

      .error {
        margin-top: 18px;
        color: #ff9a9a;
      }

      .hint {
        font-size: 13px;
      }
    `,
        ];
        render() {
            return html `
      <section class="card">
        <div class="eyebrow">Onebox secure access</div>
        ${this.renderContent()}
        ${this.errorMessage ? html `<p class="error" role="alert">${this.errorMessage}</p>` : ''}
      </section>
    `;
        }
        async firstUpdated() {
            await this.refreshAuthState();
        }
        renderContent() {
            if (this.authState === 'loading') {
                return html `<h1>Checking passkey setup…</h1>`;
            }
            if (this.authState === 'configurationRequired') {
                return html `
        <h1>Passkey setup needs a trusted hostname</h1>
        <p>${this.message}</p>
        <p class="hint">
          Configure <code>ONEBOX_ADMIN_UI_DOMAIN</code> or run
          <code>onebox config set adminUiDomain &lt;hostname&gt;</code>, then open that HTTPS URL.
        </p>
      `;
            }
            if (this.authState === 'setupRequired') {
                return html `
        <h1>Create your Onebox passkey</h1>
        <p>
          This is the only human sign-in method. The setup code is printed once in the local
          Onebox service logs and cannot be used after enrollment.
        </p>
        <label for="bootstrap-token">Passkey bootstrap code</label>
        <input
          id="bootstrap-token"
          type="text"
          autocomplete="off"
          autocapitalize="off"
          spellcheck="false"
          .value=${this.bootstrapToken}
          @input=${(eventArg) => {
                    this.bootstrapToken = eventArg.target.value.trim();
                }}
        />
        ${this.bootstrapCodeExpired
                    ? html `<p class="error">The setup code expired. Restart Onebox to rotate it.</p>`
                    : ''}
        <button
          type="button"
          ?disabled=${this.busy || !this.bootstrapToken || this.bootstrapCodeExpired}
          @click=${this.createPasskey}
        >
          ${this.busy ? 'Creating passkey…' : 'Create passkey'}
        </button>
      `;
            }
            return html `
      <h1>Sign in to Onebox</h1>
      <p>Use the passkey registered for this Onebox administrator.</p>
      <button type="button" ?disabled=${this.busy} @click=${this.signInWithPasskey}>
        ${this.busy ? 'Waiting for passkey…' : 'Sign in with passkey'}
      </button>
    `;
        }
        async refreshAuthState() {
            this.authState = 'loading';
            this.errorMessage = '';
            try {
                const request = new plugins.domtools.plugins.typedrequest.TypedRequest('/typedrequest', 'getAdminAuthState');
                const response = await request.fire({ origin: window.location.origin });
                this.authState = response.state;
                this.bootstrapCodeExpired = response.bootstrapCodeExpired;
                this.message = response.message || '';
            }
            catch (error) {
                this.authState = 'configurationRequired';
                this.message = 'Passkey authentication state is unavailable.';
                this.errorMessage = this.getErrorMessage(error);
            }
        }
        createPasskey = (__runInitializers(this, _busy_extraInitializers), async () => {
            if (!this.assertBrowserSupport())
                return;
            this.busy = true;
            this.errorMessage = '';
            try {
                const beginRequest = new plugins.domtools.plugins.typedrequest.TypedRequest('/typedrequest', 'beginAdminPasskeyRegistration');
                const beginResponse = await beginRequest.fire({
                    origin: window.location.origin,
                    bootstrapToken: this.bootstrapToken,
                });
                const registrationResponse = await plugins.simplewebauthnBrowser.startRegistration({
                    optionsJSON: beginResponse.options,
                });
                const finishRequest = new plugins.domtools.plugins.typedrequest.TypedRequest('/typedrequest', 'finishAdminPasskeyRegistration');
                const finishResponse = await finishRequest.fire({
                    ceremonyId: beginResponse.ceremonyId,
                    bootstrapToken: this.bootstrapToken,
                    response: registrationResponse,
                });
                this.dispatchAuthenticated(finishResponse.identity);
            }
            catch (error) {
                const registrationError = this.getErrorMessage(error);
                await this.refreshAuthState();
                this.errorMessage = registrationError;
            }
            finally {
                this.busy = false;
            }
        });
        signInWithPasskey = async () => {
            if (!this.assertBrowserSupport())
                return;
            this.busy = true;
            this.errorMessage = '';
            try {
                const beginRequest = new plugins.domtools.plugins.typedrequest.TypedRequest('/typedrequest', 'beginAdminPasskeyAuthentication');
                const beginResponse = await beginRequest.fire({ origin: window.location.origin });
                const authenticationResponse = await plugins.simplewebauthnBrowser.startAuthentication({
                    optionsJSON: beginResponse.options,
                });
                const finishRequest = new plugins.domtools.plugins.typedrequest.TypedRequest('/typedrequest', 'finishAdminPasskeyAuthentication');
                const finishResponse = await finishRequest.fire({
                    ceremonyId: beginResponse.ceremonyId,
                    response: authenticationResponse,
                });
                this.dispatchAuthenticated(finishResponse.identity);
            }
            catch (error) {
                this.errorMessage = this.getErrorMessage(error);
            }
            finally {
                this.busy = false;
            }
        };
        assertBrowserSupport() {
            if (!window.isSecureContext || !plugins.simplewebauthnBrowser.browserSupportsWebAuthn()) {
                this.errorMessage =
                    'Passkeys require a supported browser on the configured HTTPS origin.';
                return false;
            }
            return true;
        }
        dispatchAuthenticated(identityArg) {
            this.bootstrapToken = '';
            this.dispatchEvent(new CustomEvent('authenticated', {
                detail: { identity: identityArg },
                bubbles: true,
                composed: true,
            }));
        }
        getErrorMessage(errorArg) {
            return errorArg instanceof Error ? errorArg.message : String(errorArg);
        }
        static {
            __runInitializers(_classThis, _classExtraInitializers);
        }
    };
    return ObAuthGate = _classThis;
})();
export { ObAuthGate };
//# sourceMappingURL=data:application/json;base64, 