diff --git a/apps/pwa/package.json b/apps/pwa/package.json index b43b7024..bae7b4df 100644 --- a/apps/pwa/package.json +++ b/apps/pwa/package.json @@ -13,6 +13,7 @@ "dependencies": { "@profullstack/footer": "latest", "@profullstack/libsql-pg": "^0.1.2", + "@profullstack/profile": "0.1.6", "@simplewebauthn/browser": "^13.3.0", "@simplewebauthn/server": "^13.1.0", "cookie-parser": "^1.4.7", diff --git a/apps/pwa/src/lib/html.mjs b/apps/pwa/src/lib/html.mjs index 8b0bbd92..56c867b5 100644 --- a/apps/pwa/src/lib/html.mjs +++ b/apps/pwa/src/lib/html.mjs @@ -49,6 +49,13 @@ input:focus,textarea:focus,select:focus{outline:none;border-color:var(--green)} input::placeholder,textarea::placeholder{color:var(--faint)} label.field{display:block;margin-bottom:14px} label.field span{display:block;font-family:var(--mono);font-size:.66rem;letter-spacing:.14em;text-transform:uppercase;color:var(--faint);margin-bottom:6px} +/* the signup profile (@profullstack/profile): same look as label.field */ +.pfs-profile{border:0;padding:0;margin:0;min-width:0} +.pfs-profile__row{margin-bottom:14px} +.pfs-profile__row label{display:block;font-family:var(--mono);font-size:.66rem;letter-spacing:.14em;text-transform:uppercase;color:var(--faint);margin-bottom:6px} +.pfs-profile__optional{text-transform:none;letter-spacing:0} +.pfs-profile input[aria-invalid="true"]{border-color:var(--danger)} +.pfs-profile__error{margin:6px 0 0;font-size:.78rem;color:var(--danger)} .card{border:1px solid var(--line);border-radius:var(--r);background:var(--surface)} .card-head{display:flex;align-items:center;justify-content:space-between;gap:12px;padding:13px 16px;border-bottom:1px solid var(--line)} .card-head .h{font-family:var(--mono);font-size:.72rem;letter-spacing:.14em;text-transform:uppercase;color:var(--faint)} diff --git a/apps/pwa/src/lib/profile.mjs b/apps/pwa/src/lib/profile.mjs new file mode 100644 index 00000000..cd290b5f --- /dev/null +++ b/apps/pwa/src/lib/profile.mjs @@ -0,0 +1,45 @@ +// The signup profile (@profullstack/profile): email, first/last name, company +// domain, job title, LinkedIn URL, in user_profiles keyed by users.id. +// +// profiles the store, on the app's own client +// profileRouter GET/PUT/PATCH /api/v1/me/profile (session cookie) +// +// The package's handlers speak Web Request/Response; Express has already parsed +// the body, so it is handed back to them as JSON. +import { Router } from "express"; +import { createProfileHandlers, createProfileStore } from "@profullstack/profile"; +import { db } from "../db.mjs"; + +export const profiles = createProfileStore(db); + +const handlers = createProfileHandlers({ + store: profiles, + // Only a browser session: this is a person's own details. + getUser: (_request, req) => (req.user ? { id: req.user.id, email: req.user.email || null } : null), +}); + +function toRequest(req) { + const hasBody = !["GET", "HEAD"].includes(req.method); + return new Request(`http://localhost${req.originalUrl}`, { + method: req.method, + headers: { "content-type": "application/json", accept: "application/json" }, + body: hasBody ? JSON.stringify(req.body ?? {}) : undefined, + }); +} + +async function send(res, response) { + res.status(response.status); + response.headers.forEach((value, key) => res.set(key, value)); + res.send(Buffer.from(await response.arrayBuffer())); +} + +export const profileRouter = Router(); +for (const method of ["GET", "PUT", "PATCH"]) { + profileRouter[method.toLowerCase()]("/api/v1/me/profile", async (req, res, next) => { + try { + await send(res, await handlers[method](toRequest(req), req)); + } catch (e) { + next(e); + } + }); +} diff --git a/apps/pwa/src/migrations-pg/006_user_profiles.sql b/apps/pwa/src/migrations-pg/006_user_profiles.sql new file mode 100644 index 00000000..29425662 --- /dev/null +++ b/apps/pwa/src/migrations-pg/006_user_profiles.sql @@ -0,0 +1,14 @@ +-- Postgres edition of migrations/006_user_profiles.sql (`profile schema --key user_id --key-type text`). +create table if not exists "user_profiles" ( + "user_id" text primary key, + "email" text, + "first_name" text, + "last_name" text, + "company_domain" text, + "job_title" text, + "linkedin_url" text, + "created_at" timestamptz not null default now(), + "updated_at" timestamptz not null default now() +); +create index if not exists "user_profiles_email" on "user_profiles" (lower("email")); +create index if not exists "user_profiles_company_domain" on "user_profiles" ("company_domain"); diff --git a/apps/pwa/src/migrations/006_user_profiles.sql b/apps/pwa/src/migrations/006_user_profiles.sql new file mode 100644 index 00000000..faa6111f --- /dev/null +++ b/apps/pwa/src/migrations/006_user_profiles.sql @@ -0,0 +1,17 @@ +-- The signup profile (@profullstack/profile): email, first/last name, company +-- domain, job title, LinkedIn URL, keyed by users.id. Its own table so the +-- display_name teammates see stays as it is. No backfill: display_name holds +-- an email local-part or "logicsrc user", not a person's name. +create table if not exists "user_profiles" ( + "user_id" text primary key, + "email" text, + "first_name" text, + "last_name" text, + "company_domain" text, + "job_title" text, + "linkedin_url" text, + "created_at" text not null default (strftime('%Y-%m-%dT%H:%M:%fZ','now')), + "updated_at" text not null default (strftime('%Y-%m-%dT%H:%M:%fZ','now')) +); +create index if not exists "user_profiles_email" on "user_profiles" (lower("email")); +create index if not exists "user_profiles_company_domain" on "user_profiles" ("company_domain"); diff --git a/apps/pwa/src/routes/auth.mjs b/apps/pwa/src/routes/auth.mjs index 5bfa2d39..3b8b3492 100644 --- a/apps/pwa/src/routes/auth.mjs +++ b/apps/pwa/src/routes/auth.mjs @@ -7,10 +7,15 @@ import { createUserWithPassword, userByEmail } from "../lib/users.mjs"; import { dashboardHandler } from "./pages.mjs"; import { config } from "../config.mjs"; import { ringFooter } from "../lib/ring-footer.mjs"; +import { renderProfileFields, PROFILE_ENHANCE_SCRIPT, saveSignupProfile, validateProfile } from "@profullstack/profile"; +import { profiles } from "../lib/profile.mjs"; + +// Asked for when creating an account, beside the email box; never on sign-in. +const SIGNUP_FIELDS = ["first_name", "last_name", "company_domain", "job_title", "linkedin_url"]; export const authRouter = Router(); -function authPage(req, { error = "", mode = "in" } = {}) { +function authPage(req, { error = "", mode = "in", values = {}, errors = {} } = {}) { const body = `
LSLogicSRCcredentials @@ -20,7 +25,8 @@ function authPage(req, { error = "", mode = "in" } = {}) {
${csrfInput(req)} + + ${mode === "up" ? renderProfileFields({ fields: SIGNUP_FIELDS, values, errors, idPrefix: "signup-" }) : ""} @@ -41,7 +47,7 @@ function authPage(req, { error = "", mode = "in" } = {}) {
${footer}${ringFooter()} - `; + ${mode === "up" ? `` : ""}`; return page({ title: "LogicSRC ▸ sign in", body }); } @@ -57,10 +63,22 @@ authRouter.get("/", (req, res) => { authRouter.post("/auth/register", async (req, res) => { const email = String(req.body.email || "").trim().toLowerCase(); const password = String(req.body.password || ""); - if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email)) return res.type("html").send(authPage(req, { mode: "up", error: "Enter a valid email." })); - if (password.length < 8) return res.type("html").send(authPage(req, { mode: "up", error: "Password must be at least 8 characters." })); - if (await userByEmail(email)) return res.type("html").send(authPage(req, { mode: "up", error: "That email already has an account — sign in." })); + // What was typed comes back on a refused form (never the password). + const values = Object.fromEntries(["email", ...SIGNUP_FIELDS].map((f) => [f, String(req.body[f] ?? "")])); + const refuse = (error, errors = {}) => res.type("html").send(authPage(req, { mode: "up", error, values, errors })); + if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(email)) return refuse("Enter a valid email."); + // The profile is checked before the account exists, so a refused form leaves nothing half-made. + const check = validateProfile(req.body); + if (!check.ok) return refuse("A few of those fields need another look.", check.errors); + if (password.length < 8) return refuse("Password must be at least 8 characters."); + if (await userByEmail(email)) return refuse("That email already has an account — sign in."); const user = await createUserWithPassword(email, hashPassword(password)); + // A failed profile write never fails the signup; Settings can fill it in. + try { + await saveSignupProfile(profiles, user.id, req.body, { email }); + } catch (e) { + console.error("signup profile save failed:", e); + } await createSession(res, user.id); res.redirect(takeNext(req, res) || "/"); }); diff --git a/apps/pwa/src/routes/pages.mjs b/apps/pwa/src/routes/pages.mjs index b07b703a..d16f769c 100644 --- a/apps/pwa/src/routes/pages.mjs +++ b/apps/pwa/src/routes/pages.mjs @@ -12,6 +12,8 @@ import { requestOrigin } from "../lib/origin.mjs"; import { CLI_HINT } from "../lib/cli-hint.mjs"; import { vaultPageBody } from "../lib/vault-page.mjs"; import { config } from "../config.mjs"; +import { COLUMNS, renderProfileFields, validateProfile } from "@profullstack/profile"; +import { profiles } from "../lib/profile.mjs"; import { TeamMemberError, canManageMember, @@ -272,6 +274,9 @@ function keyRow(req, k) { pagesRouter.get("/settings", requireAuth, async (req, res) => { const keys = await listApiKeys(req.user.id); + const mine = (await profiles.get(req.user.id)) ?? {}; + const profileValues = Object.fromEntries(COLUMNS.map((c) => [c, mine[c] ?? null])); + profileValues.email ??= req.user.email || null; const teams = await all(`SELECT t.slug FROM credshare_teams t JOIN credshare_members m ON m.team_id = t.id WHERE m.user_id = ? AND m.status = 'active' ORDER BY t.slug`, [req.user.id]); const newKey = req.query.key ? String(req.query.key) : ""; const err = req.query.err ? String(req.query.err).slice(0, 200) : ""; @@ -281,6 +286,14 @@ pagesRouter.get("/settings", requireAuth, async (req, res) => {

Settings

${newKey ? `
New API key (copy it now — shown once):
${esc(newKey)}
` : ""} ${err ? `
${esc(KEY_ERRORS[err] || err)}
` : ""} + ${req.query.saved === "profile" ? `
Your details are saved.
` : ""} +
Your details
+
+ ${csrfInput(req)} + ${renderProfileFields({ values: profileValues, required: ["first_name", "last_name"], idPrefix: "account-" })} + + +
API keys

A person key acts as you; logicsrc login makes one for you. A machine key is for a deploy box or CI: one team, the vaults you list, read-only unless you say otherwise, its own identity key. After the box runs one command with it, grant it a vault from the vault page or with logicsrc teams grant <team> <project> <env> --key <name>.

@@ -308,6 +321,15 @@ pagesRouter.get("/settings", requireAuth, async (req, res) => { res.type("html").send(page({ title: "LogicSRC ▸ settings", body })); }); +// The signup profile, editable. Names are required; the email falls back to the account's. +pagesRouter.post("/settings/profile", requireAuth, async (req, res) => { + const input = { ...req.body, email: String(req.body.email || "").trim() || req.user.email || "" }; + const check = validateProfile(input, { required: ["first_name", "last_name"] }); + if (!check.ok) return res.redirect(`/settings?err=${encodeURIComponent(`Check your details: ${Object.values(check.errors).join(" ")}`)}`); + await profiles.save(req.user.id, check.profile); + res.redirect("/settings?saved=profile"); +}); + pagesRouter.post("/settings/apikeys", requireAuth, async (req, res) => { const name = String(req.body.name || "").trim().slice(0, 40); if (!name) return res.redirect("/settings?err=no-name"); diff --git a/apps/pwa/src/server.mjs b/apps/pwa/src/server.mjs index dd6562d1..a73681da 100644 --- a/apps/pwa/src/server.mjs +++ b/apps/pwa/src/server.mjs @@ -14,6 +14,7 @@ import { apiKeysRouter } from "./routes/apikeys.mjs"; import { opencredsRouter } from "./routes/opencreds.mjs"; import { cliRouter } from "./routes/cli.mjs"; import { pagesRouter } from "./routes/pages.mjs"; +import { profileRouter } from "./lib/profile.mjs"; import { descriptor } from "@profullstack/footer"; import { RING_FOOTER_OPTIONS, startRingFooterRefresh } from "./lib/ring-footer.mjs"; @@ -67,6 +68,7 @@ app.use(credshareRouter); // /api/credshare/* (session or lsk_ Bearer) app.use(apiKeysRouter); // /api/keys (session or a person's lsk_ key; never a machine key) app.use(opencredsRouter); // /api/opencreds/* — personal vault sync (session or lsk_ Bearer) app.use(cliRouter); // /cli/authorize, /cli/token, /api/me +app.use(profileRouter); // /api/v1/me/profile (session cookie) app.use(pagesRouter); // /dashboard, /teams/*, /settings app.use((req, res) => res.status(404).type("html").send( diff --git a/apps/pwa/test/signup-profile.test.mjs b/apps/pwa/test/signup-profile.test.mjs new file mode 100644 index 00000000..fbe4cf31 --- /dev/null +++ b/apps/pwa/test/signup-profile.test.mjs @@ -0,0 +1,95 @@ +// The signup profile (@profullstack/profile): /?mode=up asks for it, the +// register handler validates and stores it, /api/v1/me/profile serves it. +process.env.DATABASE_URL = process.env.PWA_TEST_DATABASE_URL || ":memory:"; + +import test from "node:test"; +import assert from "node:assert/strict"; +import { readFileSync } from "node:fs"; +import { fileURLToPath } from "node:url"; +import { dirname, join } from "node:path"; +import express from "express"; +import cookieParser from "cookie-parser"; + +const here = dirname(fileURLToPath(import.meta.url)); +const { db, get, isPostgres } = await import("../src/db.mjs"); +const { sessionMiddleware } = await import("../src/lib/session.mjs"); +const { authRouter } = await import("../src/routes/auth.mjs"); +const { profileRouter } = await import("../src/lib/profile.mjs"); + +if (isPostgres) { + await db.execute("DROP SCHEMA public CASCADE"); + await db.execute("CREATE SCHEMA public"); +} +for (const file of ["001_auth.sql", "006_user_profiles.sql"]) { + const sql = readFileSync(join(here, "..", "src", isPostgres ? "migrations-pg" : "migrations", file), "utf8"); + for (const statement of sql.split(/;\s*$/m).map((s) => s.trim()).filter(Boolean)) await db.execute(statement); +} + +async function serve() { + const app = express(); + app.use(express.json()); + app.use(express.urlencoded({ extended: false })); + app.use(cookieParser()); + app.use(sessionMiddleware); + app.use(authRouter); + app.use(profileRouter); + const server = app.listen(0); + await new Promise((resolve) => server.once("listening", resolve)); + const base = `http://127.0.0.1:${server.address().port}`; + return { + fetch: (path, init = {}) => fetch(`${base}${path}`, { redirect: "manual", ...init }), + close: () => new Promise((resolve) => server.close(resolve)), + }; +} + +const form = (fields) => ({ + method: "POST", + headers: { "content-type": "application/x-www-form-urlencoded" }, + body: new URLSearchParams(fields).toString(), +}); + +test("the signup form asks for the profile; sign-in does not", async (t) => { + const app = await serve(); + t.after(() => app.close()); + assert.match(await (await app.fetch("/?mode=up")).text(), /name="job_title"/); + assert.doesNotMatch(await (await app.fetch("/?mode=in")).text(), /name="job_title"/); +}); + +test("a signup without a last name is refused and creates no account", async (t) => { + const app = await serve(); + t.after(() => app.close()); + const res = await app.fetch("/auth/register", form({ email: "nolast@acme.com", password: "longenough1", first_name: "Ada" })); + assert.equal(res.status, 200); + assert.match(await res.text(), /pfs-profile__error/); + assert.equal(await get(`SELECT id FROM users WHERE email = ?`, ["nolast@acme.com"]), null); +}); + +test("a signup stores the six fields, normalized, and /api/v1/me/profile serves them", async (t) => { + const app = await serve(); + t.after(() => app.close()); + const res = await app.fetch("/auth/register", form({ + email: "Ada@Acme.com", + password: "longenough1", + first_name: "Ada", + last_name: "Lovelace", + company_domain: "https://www.acme.com/about", + job_title: "VP Engineering", + linkedin_url: "in/ada-lovelace", + })); + assert.equal(res.status, 302); + const cookie = res.headers.getSetCookie().map((c) => c.split(";")[0]).join("; "); + + const me = await app.fetch("/api/v1/me/profile", { headers: { cookie } }); + assert.equal(me.status, 200); + const body = await me.json(); + const profile = body.profile ?? body; + assert.equal(profile.email, "ada@acme.com"); + assert.equal(profile.first_name, "Ada"); + assert.equal(profile.last_name, "Lovelace"); + assert.equal(profile.company_domain, "acme.com"); + assert.equal(profile.job_title, "VP Engineering"); + assert.equal(profile.linkedin_url, "https://www.linkedin.com/in/ada-lovelace"); + + const anon = await app.fetch("/api/v1/me/profile"); + assert.equal(anon.status, 401); +}); diff --git a/bun.lock b/bun.lock index 5c8b2159..c4ccdc15 100644 --- a/bun.lock +++ b/bun.lock @@ -84,6 +84,7 @@ "dependencies": { "@profullstack/footer": "latest", "@profullstack/libsql-pg": "^0.1.2", + "@profullstack/profile": "0.1.6", "@simplewebauthn/browser": "^13.3.0", "@simplewebauthn/server": "^13.1.0", "cookie-parser": "^1.4.7", @@ -813,6 +814,8 @@ "@profullstack/logicsrc-mcp": ["@profullstack/logicsrc-mcp@workspace:packages/logicsrc-mcp"], + "@profullstack/profile": ["@profullstack/profile@0.1.6", "", { "peerDependencies": { "@libsql/client": ">=0.6.0", "postgres": "^3.4.0", "react": ">=18" }, "optionalPeers": ["@libsql/client", "postgres", "react"], "bin": { "profile": "src/cli.js" } }, "sha512-xkn0P3ANz151QJdlBwcBXkHk813qW9qAmuTZKcuvpEZYkyHDC9J9KfvpVSRepfjECzz4ONGHWO5Zwc4BHpfK8g=="], + "@profullstack/referrals": ["@profullstack/referrals@0.1.0", "", { "peerDependencies": { "react": ">=18" }, "optionalPeers": ["react"] }, "sha512-u66SdBVpsv3kc0N+NWISPoYD5vjCERyv5wfD07iSkZwQeC2IA+ihX5jNA4e7Xr+Y4AUvxLycG+3b4VaROqzgRg=="], "@profullstack/stack": ["@profullstack/stack@0.1.3", "", { "dependencies": { "@profullstack/emailer": "^1.0.1", "@profullstack/referrals": "^0.1.0" }, "peerDependencies": { "@supabase/ssr": ">=0.5.0", "next": ">=13.0.0", "react": ">=18.0.0" }, "optionalPeers": ["@supabase/ssr", "next", "react"] }, "sha512-NOseYE5cWMwH75/luUE46kJLyAd1xD+DSgGgwhxvgNMoJYfZ9W9vKmqdcGA/4Lgahzf7hWfjNvmLtVIzAqwhJw=="],