ident
All repositories: gitoria
9.0 KB
// selector.js — ident's IDENTITY SELECTOR for an app's page (piece 3 of 6, ticket #26;// CONCEPT.md "Flow 2: identity selector"). Served by ident at /selector.js. An app's page://// <script src="https://<ident>/selector.js"></script>// <ident-selector key="pk_…"></ident-selector> (the app's PUBLIC API key)//// The element (shadow DOM, ident's design) first says "choose ident". Opening it fetches// the identities of the ident user signed in in this browser from ident (credentials,// CORS: only from one of the app's registered origins with its key). Choosing one IS the// login: ident hands a one-time code, the element fires `ident-login` with// `event.detail.code`; the HOST'S SERVER trades the code with POST /api/exchange (key +// secret) for the app-specific identity id.// The host tells the element it is logged in: attribute `logged-in` (or `el.loggedIn =// true`). Logout on the website = the host resets it (remove the attribute, or// `el.loggedIn = false` / `el.reset()`). The element sets no cookie of its own.// Signed out of ident, the panel holds ident's own sign-in page in an iframe (/embed/signin; ident frames it only for the app's origins).// Restyling: CSS custom properties --ident-* on the element, and ::part(button | panel |// identity | status | message | link) — see ident's README "How apps use ident".(() => {if (!window.customElements || customElements.get('ident-selector')) return;const script = document.currentScript;const IDENT = new URL(script ? script.src : location.href).origin;const CSS = `:host {--_accent: var(--ident-accent, #ce9178);--_accent-text: var(--ident-accent-text, rgb(15, 20, 25));--_bg: var(--ident-background, rgb(35, 40, 45));--_text: var(--ident-text, rgb(195, 200, 205));--_strong: var(--ident-text-strong, rgb(245, 250, 255));--_muted: var(--ident-text-muted, rgb(145, 150, 155));--_border: var(--ident-border, rgb(70, 75, 80));--_radius: var(--ident-radius, .4rem);display: inline-block;max-width: 100%;font: var(--ident-font, 600 16px/1.5 system-ui, sans-serif);color: var(--_text);}:host([hidden]) { display: none; }* { box-sizing: border-box; }button { font: inherit; cursor: pointer; }[part~="button"] {display: inline-flex; align-items: center; gap: .5rem; max-width: 100%;padding: .6rem 1.1rem; color: var(--_accent-text); background: var(--_accent);border: 1px solid var(--_accent); border-radius: var(--_radius);}[part~="button"]:hover { filter: brightness(1.1); }[part~="button"]:focus-visible, [part~="identity"]:focus-visible { outline: 2px solid var(--_strong); outline-offset: 2px; }.mark { font-weight: 800; letter-spacing: .01em; }.caret { font-size: .75em; }[part~="panel"] {margin-top: .4rem; width: 20rem; max-width: 100%; padding: .5rem;background: var(--_bg); border: 1px solid var(--_border); border-radius: calc(var(--_radius) * 1.5);font-weight: 400;}ul { list-style: none; margin: 0; padding: 0; display: grid; gap: .3rem; }[part~="identity"] {display: block; width: 100%; text-align: left; padding: .55rem .8rem; overflow-wrap: anywhere;color: var(--_strong); background: transparent; border: 1px solid var(--_border); border-radius: var(--_radius);}[part~="identity"]:hover { border-color: var(--_accent); color: var(--_accent); }iframe { display: block; width: 100%; height: 19.5rem; /* until the frame reports its height */ border: 0; background: transparent; }@media (min-width: 600px) { iframe { height: 21rem; } }.head { margin: 0 0 .4rem; font-size: .85rem; color: var(--_muted); }[part~="message"] { margin: 0; padding: .3rem .2rem; font-size: .95rem; }[part~="link"] { color: var(--_accent); }[part~="status"] {display: inline-flex; align-items: center; gap: .5rem; max-width: 100%; overflow-wrap: anywhere;padding: .6rem 1.1rem; color: var(--_strong); background: var(--_bg);border: 1px solid var(--_border); border-radius: var(--_radius);}[part~="status"] .check { color: var(--_accent); }`;const esc = (s) => String(s).replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' })[c]);class IdentSelector extends HTMLElement {static get observedAttributes() { return ['logged-in', 'key']; }constructor() {super();this.attachShadow({ mode: 'open' });this._open = false;this._view = 'idle'; // idle | loading | list | signedout | errorthis._items = [];this._error = '';this._chosen = '';this._render();// the sign-in frame tells its content height (ident's /embed/signin, per step); only ident's own window is believedwindow.addEventListener('message', (e) => {const f = this.shadowRoot.getElementById('signin');const h = e.data && e.data.identFrameHeight;if (f && e.origin === IDENT && e.source === f.contentWindow && h > 0 && h < 3000) f.style.height = Math.ceil(h) + 'px';});}get key() { return this.getAttribute('key') || ''; }// where ident sends the browser after the sign-in (?ident_code=…): the attribute `return` (an absolute URL on the app's origin that handles// ident_code, e.g. the login button's), else this pageget returnUrl() { return this.getAttribute('return') || location.href.split('#')[0]; }get loggedIn() { return this.hasAttribute('logged-in'); }set loggedIn(v) { this.toggleAttribute('logged-in', !!v); }reset() { this.loggedIn = false; }attributeChangedCallback(name) {if (name === 'logged-in' && !this.loggedIn) this._chosen = '';this._open = false;this._render();}async _toggle() {if (this._open) { this._open = false; this._render(); return; }this._open = true;this._view = 'loading';this._render();try {const r = await fetch(IDENT + '/api/selector/identities?key=' + encodeURIComponent(this.key), { credentials: 'include', cache: 'no-store' });if (!r.ok) throw new Error('HTTP ' + r.status);const j = await r.json();this._items = j.identities || [];this._view = j.signedIn ? 'list' : 'signedout';} catch (e) {// a refused origin/key has no CORS headers: the browser gives us nothing but thisthis._view = 'error';this._error = 'ident does not answer this site. Is it registered in ident with this API key?';}if (this._open) this._render();}async _choose(id, name) {this._view = 'loading';this._render();try {const r = await fetch(IDENT + '/api/selector/choose?key=' + encodeURIComponent(this.key), {method: 'POST', credentials: 'include', cache: 'no-store',headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ identity: id }),});const j = await r.json().catch(() => ({}));if (!r.ok || !j.code) throw new Error(j.error || ('HTTP ' + r.status));this._chosen = name;this._open = false;this._render();// THE LOGIN: the host's server trades this code (POST /api/exchange, key + secret)this.dispatchEvent(new CustomEvent('ident-login', { detail: { code: j.code }, bubbles: true, composed: true }));} catch (e) {this._view = 'error';this._error = 'ident refused: ' + e.message;this._render();}}_render() {const root = this.shadowRoot;if (this.loggedIn) {root.innerHTML = `<style>${CSS}</style><span part="status" id="status"><span class="check" aria-hidden="true">✓</span>` +`<span>logged in with <span class="mark">ident</span>${this._chosen ? ' · ' + esc(this._chosen) : ''}</span></span>`;return;}let panel = '';if (this._open) {let body = '';if (this._view === 'loading') body = `<p part="message" id="message">…</p>`;else if (this._view === 'list') {body = `<p class="head">Choose the identity to log in with</p><ul id="list">` +this._items.map((it) => `<li><button type="button" part="identity" data-id="${esc(it.id)}">${esc(it.name)}</button></li>`).join('') + `</ul>`;} else if (this._view === 'signedout') {body = `<iframe part="frame" id="signin" title="Sign in to ident" src="${esc(IDENT)}/embed/signin?key=${encodeURIComponent(this.key)}&return=${encodeURIComponent(this.returnUrl)}"></iframe>`;} else if (this._view === 'error') body = `<p part="message" id="message">${esc(this._error)}</p>`;panel = `<div part="panel" id="panel">${body}</div>`;}root.innerHTML = `<style>${CSS}</style><button type="button" part="button" id="choose" aria-expanded="${this._open}">` +`<span>choose <span class="mark">ident</span></span><span class="caret" aria-hidden="true">${this._open ? '▲' : '▼'}</span></button>${panel}`;root.getElementById('choose').addEventListener('click', () => this._toggle());for (const b of root.querySelectorAll('[part~="identity"]')) {b.addEventListener('click', () => this._choose(b.dataset.id, b.textContent));}}}customElements.define('ident-selector', IdentSelector);})();
Branches
Latest commits
- 07d1717c|||PR ident#40 home.hl is split into components, one per area: email step, identity form, identity list, app identity choice, time zone; each moves its faces with it, the email step is shared with embed.hl (#40.3, rest of #40.2)mre
- 59e8fcc1ident#40.3: the app's identity choice is one component (components/chooseidentity.hl); its face chooseIdentity moves with itmre
- e23efdfcident#40.3: the identity list is one component (components/identitylist.hl); its delete and face dropIdentity move with itmre
- e24b59a6ident#40.3: the time zone is one component (components/timezone.hl); its face changeTimeZone moves with itmre
- 8cbc5717ident#40.3: the email step is one component (components/emailstep.hl) placed by home.hl and embed.hlmre
- 6fad3bd2Merge branch 'f3-codestep' into mainIdent
- 51e387f2|||PR ident#40 the code step is one component (components/codestep.hl) placed by home.hl and embed.hl; its verify face, setCode, browserZone and verify call exist once (#40.2)mre
- c28bddeeMerge branch 'f2-shell' into mainIdent
- c3a40ff6|||PR ident#40 one shell for the app and /start (account part off on /start, #40.1); startshell.hl removed; unused signOut faces gone (#40.4)mre
- 060f3870ident#40.4: use the shell sign-out faces in regression gatesmre
- 9b94aa6aMerge branch 'f1b-cleanup' into mainIdent
- edcfce3f|||PR ident#41 ident#43 ident#44 login error page as a component (same status codes and text, pixel-identical), declarations and route wiring cleaned upmre
- 3ac85995ident#43 ident#44: plain declarations for never-reassigned lets, one envString helper, named route functions and audience rule out of project.hlmre
- c7eef14aMerge branch 'nv1-navigate' into mainIdent
- 644f9775|||PR ident#36 navigate() instead of window.location in the shell, start shell and homemre
- 4ca2f921deploy.sh: tar --hard-dereference so backups hold no hard linksmre
- 23971fb7ident#49: media queries in the language's @media formmre
- 73f4f97dident: re-vendor to hybriel day38b (mpackdb store-open fix)mre
- aa056c03ident: a startup error prints its message before exit 1 (hybriel#247)mre
- ee37a861ident#G48: gitoria's registration gets the wildcard origin of its repo addresses at load (gate tests/gitoria-origin.mjs)mre