@pwfabric/cli 1.0.0 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"local-host.js","sourceRoot":"","sources":["../../src/host/local-host.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AAGH,OAAO,EACL,SAAS,EACT,SAAS,EACT,YAAY,EACZ,cAAc,EACd,QAAQ,EACR,YAAY,EACZ,SAAS,EACT,QAAQ,GACT,MAAM,WAAW,CAAA;AAClB,OAAO,EACL,QAAQ,EACR,YAAY,EACZ,WAAW,EACX,WAAW,GAGZ,MAAM,kBAAkB,CAAA;AACzB,OAAO,EAAE,WAAW,EAAe,MAAM,cAAc,CAAA;AACvD,OAAO,EAAE,oBAAoB,EAAE,MAAM,eAAe,CAAA;AACpD,OAAO,EAAE,SAAS,EAAc,MAAM,WAAW,CAAA;AACjD,OAAO,EAAE,UAAU,EAAkB,MAAM,aAAa,CAAA;AAGxD,MAAM,CAAC,MAAM,gBAAgB,GAAG,EAAE,EAAE,EAAE,UAAU,EAAE,IAAI,EAAE,WAAW,EAAE,KAAK,EAAE,eAAe,EAAW,CAAA;AAEtG,qEAAqE;AACrE,MAAM,CAAC,MAAM,cAAc,GAAG,iBAAiB,CAAA;AAE/C,MAAM,cAAc,GAAG,CAAC,GAAG,QAAQ,CAAA;AACnC,MAAM,kBAAkB,GAAG,CAAC,GAAG,MAAM,CAAA;AAErC,kGAAkG;AAClG,MAAM,gBAAgB,GAAG,IAAI,GAAG,CAAC,CAAC,SAAS,EAAE,QAAQ,EAAE,QAAQ,EAAE,WAAW,CAAC,CAAC,CAAA;AAE9E,SAAS,eAAe,CAAC,MAAc;IACrC,MAAM,OAAO,GAAG,MAAM,CAAC,OAAO,CAAC,YAAY,EAAE,EAAE,CAAC,CAAA;IAChD,IAAI,CAAC,OAAO;QAAE,MAAM,IAAI,KAAK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the data protocol, in process,\n * for development.\n *\n * NOT A PRODUCTION SERVER. Records live in memory and vanish on restart; the\n * one development user signs in without a password; the issuer stand-in mints\n * unsigned ID tokens; there is no rate limit, no CORS, no TLS. It exists so an\n * app that declares data and sign-in runs on a laptop with no hosted service,\n * and so the runner's sign-in wall, account control, gate and data paths are\n * exercised against the same addresses and answers a session server gives.\n *\n * Everything is mounted under `prefix` (e.g. `/_host`); `<base>` below is\n * `<origin><prefix>`, which is also the app's own API base the runner derives\n * from `loginUrl` (session-protocol §2).\n *\n * App door (session-protocol §4, §8)\n * POST <base>/login, <base>/register any credentials → the development user\n * POST <base>/logout revokes the presented token\n * GET <base>/session the principal behind the token\n * GET <base>/_auth/start/<method> provider sign-in, through the same redirects\n * GET <base>/_auth/callback/<method> …ends here: HttpOnly cookie, back to returnTo\n * GET <base>/_auth/session the cookie's session (needs x-pwapp-request: 1)\n * POST <base>/_auth/logout deletes the cookie (needs x-pwapp-request: 1)\n * External issuer stand-in (session-protocol §3) — see ./oidc.ts\n * GET <base>/oidc/.well-known/openid-configuration, GET <base>/oidc/authorize,\n * POST <base>/oidc/token\n * Records (data-protocol §5) — see ./records.ts\n * GET|POST <base>/records/<T>, GET <base>/records/<T>/count, GET <base>/records/<T>/aggregate,\n * GET|PATCH|DELETE <base>/records/<T>/<id>\n * Pages\n * GET <base>/surfaces/<key>.receipt.json the receipt, entity sources rewritten to <base>,\n * refused without a session when sign-in is required\n *\n * Every credential is accepted on `x-app-session` or `Authorization: Bearer`.\n * Tokens are opaque and random, kept only as hashes, and never logged.\n */\n\nimport type { IncomingMessage, ServerResponse } from 'node:http'\nimport {\n HostError,\n cookiesOf,\n credentialOf,\n readJsonObject,\n redirect,\n safeReturnTo,\n sendError,\n sendJson,\n} from './http.js'\nimport {\n readAuth,\n readEntities,\n readReceipt,\n surfaceKeys,\n type AuthDeclaration,\n type EntityDeclaration,\n} from './definitions.js'\nimport { RecordStore, type Target } from './records.js'\nimport { rewriteEntitySources } from './receipts.js'\nimport { DevIssuer, type Grant } from './oidc.js'\nimport { TokenStore, type Principal } from './tokens.js'\nimport type { CreateLocalHost, LocalHost, LocalHostOptions } from './types.js'\n\nexport const DEFAULT_DEV_USER = { id: 'dev-user', name: 'Developer', email: 'dev@localhost' } as const\n\n/** The cookie the provider round trip leaves on the app's origin. */\nexport const SESSION_COOKIE = 'pwf_dev_session'\n\nconst SESSION_TTL_MS = 8 * 3600_000\nconst TRANSACTION_TTL_MS = 5 * 60_000\n\n/** The provider buttons a session server can name (envelope `auth.json` `providers[].method`). */\nconst PROVIDER_METHODS = new Set(['phiwebs', 'google', 'github', 'microsoft'])\n\nfunction normalisePrefix(prefix: string): string {\n const trimmed = prefix.replace(/^\\/+|\\/+$/g, '')\n if (!trimmed) throw new Error('createLocalHost: prefix must name a path, e.g. \"/_host\"')\n return `/${trimmed}`\n}\n\nfunction providersOf(auth: AuthDeclaration): string[] {\n return auth.methods.filter((m) => PROVIDER_METHODS.has(m))\n}\n\n/**\n * The envelope `auth.json` for this declaration, pointed at `base` — the\n * same shape a publisher writes (session-protocol §2), or `undefined` when the\n * app has no way in.\n *\n * - `external`: `oauth2-pkce` against the local issuer stand-in, keeping the\n * declared client id, scopes (plus `offline_access`, which is what makes a\n * refresh token exist) and audience.\n * - `app`: the password door when `password` is declared; the provider\n * buttons and the start address for every declared provider method; the\n * gateway's session and logout addresses for either; `methods` as declared.\n */\nexport function authAddresses(auth: AuthDeclaration | undefined, base: string): Record<string, unknown> | undefined {\n if (!auth) return undefined\n if (auth.topology === 'external') {\n if (!auth.issuer) return undefined\n const scopes = auth.issuer.scopes.includes('offline_access')\n ? [...auth.issuer.scopes]\n : [...auth.issuer.scopes, 'offline_access']\n return {\n provider: 'oauth2-pkce',\n issuer: `${base}/oidc`,\n clientId: auth.issuer.clientId,\n scopes,\n ...(auth.issuer.audience ? { audience: auth.issuer.audience } : {}),\n }\n }\n const door: Record<string, unknown> = {}\n if (auth.methods.includes('password')) {\n door.provider = 'password'\n door.loginUrl = `${base}/login`\n door.registerUrl = `${base}/register`\n door.logoutUrl = `${base}/logout`\n door.sessionUrl = `${base}/session`\n }\n const providers = providersOf(auth)\n if (providers.length > 0) {\n door.provider = door.provider ?? 'platform'\n door.providers = providers.map((method) => ({ method }))\n door.startUrl = `${base}/_auth/start`\n door.gatewaySessionUrl = `${base}/_auth/session`\n door.gatewayLogoutUrl = `${base}/_auth/logout`\n }\n if (Object.keys(door).length === 0) return undefined\n // The runner asks the gateway on every app door, not only a provider one:\n // for a stored-nothing session on boot, and on every sign-out (it falls back\n // to `/_auth/session` and `/_auth/logout` at the page's origin, which on\n // `pwf dev` are not the host's). The host answers both under its base.\n door.gatewaySessionUrl ??= `${base}/_auth/session`\n door.gatewayLogoutUrl ??= `${base}/_auth/logout`\n door.methods = [...auth.methods]\n return door\n}\n\nfunction segments(rest: string): string[] {\n try {\n return rest.split('/').filter(Boolean).map((s) => decodeURIComponent(s))\n } catch {\n throw new HostError(400, 'INVALID_PATH', 'The path is not valid percent-encoding.')\n }\n}\n\nfunction methodNotAllowed(): never {\n throw new HostError(405, 'METHOD_NOT_ALLOWED', 'This route does not take that method.')\n}\n\nfunction notFound(): never {\n throw new HostError(404, 'NOT_FOUND', 'No such route on the local host.')\n}\n\nexport const createLocalHost: CreateLocalHost = (options: LocalHostOptions): LocalHost => {\n const root = options.root\n const prefix = normalisePrefix(options.prefix)\n const user: Principal = {\n id: options.user?.id ?? DEFAULT_DEV_USER.id,\n email: options.user?.email ?? DEFAULT_DEV_USER.email,\n displayName: options.user?.name ?? DEFAULT_DEV_USER.name,\n }\n\n const bearer = new TokenStore<Grant>()\n const transactions = new TokenStore<{ readonly returnTo: string; readonly method: string; readonly expiresAt: number }>()\n const records = new RecordStore(root, user)\n const issuer = new DevIssuer(bearer, user)\n\n const originOf = (req: IncomingMessage): string => `http://${req.headers.host ?? 'localhost'}`\n\n const principalOf = (req: IncomingMessage): Principal | undefined => bearer.get(credentialOf(req))?.principal\n\n function startSession(): { token: string; expiresAt: string; principal: Principal } {\n const expiresAt = Date.now() + SESSION_TTL_MS\n const token = bearer.issue({ principal: user, kind: 'session', expiresAt })\n return { token, expiresAt: new Date(expiresAt).toISOString(), principal: user }\n }\n\n const sessionCookie = (token: string, maxAgeS: number): string =>\n `${SESSION_COOKIE}=${encodeURIComponent(token)}; Path=${prefix}/_auth; HttpOnly; SameSite=Lax; Max-Age=${maxAgeS}`\n\n function requireRunnerRequest(req: IncomingMessage): void {\n if (req.headers['x-pwapp-request'] !== '1') {\n throw new HostError(403, 'RUNNER_REQUEST_REQUIRED', 'This address answers only the runner (x-pwapp-request: 1).')\n }\n }\n\n // ---------------------------------------------------------------- app door\n\n async function door(req: IncomingMessage, res: ServerResponse, action: string): Promise<void> {\n const auth = readAuth(root)\n if (action === 'session') {\n if (req.method !== 'GET') methodNotAllowed()\n const presented = credentialOf(req)\n const grant = bearer.get(presented)\n if (grant) {\n sendJson(res, 200, { data: { principal: grant.principal } })\n return\n }\n if (presented !== undefined || auth?.required) {\n throw new HostError(401, 'SIGN_IN_REQUIRED', 'No live session.')\n }\n sendJson(res, 200, { data: { principal: null } })\n return\n }\n if (req.method !== 'POST') methodNotAllowed()\n if (action === 'logout') {\n bearer.revoke(credentialOf(req))\n sendJson(res, 200, { data: { signedOut: true } })\n return\n }\n // login / register: the credentials are read (and must be JSON) but not\n // checked — the development user has no password.\n await readJsonObject(req)\n if (!auth || auth.topology !== 'app' || !auth.methods.includes('password')) {\n throw new HostError(404, 'NO_PASSWORD_DOOR', 'This app declares no password sign-in.')\n }\n sendJson(res, action === 'register' ? 201 : 200, { data: startSession() })\n }\n\n function gateway(req: IncomingMessage, res: ServerResponse, url: URL, parts: string[]): void {\n const [action, method] = parts\n if (action === 'start' || action === 'callback') {\n if (req.method !== 'GET') methodNotAllowed()\n if (parts.length !== 2 || !method) notFound()\n if (action === 'start') {\n const returnTo = safeReturnTo(url.searchParams.get('returnTo'))\n const auth = readAuth(root)\n if (!auth || auth.topology !== 'app' || !providersOf(auth).includes(method)) {\n redirect(res, withAuthError(returnTo, 'provider_unavailable'))\n return\n }\n // The provider's own leg is played by the callback below: the browser\n // still leaves the app, comes back to the callback, and lands on returnTo.\n const tx = transactions.issue({ returnTo, method, expiresAt: Date.now() + TRANSACTION_TTL_MS })\n redirect(res, `${prefix}/_auth/callback/${encodeURIComponent(method)}?tx=${encodeURIComponent(tx)}`)\n return\n }\n const tx = transactions.take(url.searchParams.get('tx') ?? undefined)\n if (!tx || tx.method !== method) {\n redirect(res, withAuthError('/', 'invalid_transaction'))\n return\n }\n const session = startSession()\n redirect(res, tx.returnTo, [sessionCookie(session.token, SESSION_TTL_MS / 1000)])\n return\n }\n if (parts.length !== 1) notFound()\n if (action === 'session') {\n if (req.method !== 'GET') methodNotAllowed()\n requireRunnerRequest(req)\n const token = cookiesOf(req)[SESSION_COOKIE]\n const grant = bearer.get(token)\n if (!token || !grant || grant.kind !== 'session') {\n throw new HostError(401, 'SIGN_IN_REQUIRED', 'No session cookie.')\n }\n sendJson(res, 200, {\n data: { token, expiresAt: new Date(grant.expiresAt).toISOString(), principal: grant.principal },\n })\n return\n }\n if (action === 'logout') {\n if (req.method !== 'POST') methodNotAllowed()\n requireRunnerRequest(req)\n bearer.revoke(cookiesOf(req)[SESSION_COOKIE])\n sendJson(res, 200, { data: { signedOut: true } }, { 'set-cookie': sessionCookie('', 0) })\n return\n }\n notFound()\n }\n\n // ------------------------------------------------------------------ issuer\n\n async function oidc(req: IncomingMessage, res: ServerResponse, url: URL, parts: string[]): Promise<void> {\n const auth = readAuth(root)\n if (!auth || auth.topology !== 'external' || !auth.issuer) {\n throw new HostError(404, 'NO_ISSUER', 'This app declares no external issuer.')\n }\n const iss = DevIssuer.issuerUrl(originOf(req), prefix)\n const route = parts.join('/')\n if (route === '.well-known/openid-configuration') {\n if (req.method !== 'GET') methodNotAllowed()\n issuer.discovery(res, iss)\n return\n }\n if (route === 'authorize') {\n if (req.method !== 'GET') methodNotAllowed()\n issuer.authorize(req, res, url, auth)\n return\n }\n if (route === 'token') {\n if (req.method !== 'POST') methodNotAllowed()\n await issuer.token(req, res, iss, auth)\n return\n }\n notFound()\n }\n\n // ----------------------------------------------------------------- records\n\n function entityOf(typeId: string): EntityDeclaration {\n const entity = readEntities(root).find((e) => e.typeId === typeId)\n if (!entity) throw new HostError(404, 'UNKNOWN_ENTITY_TYPE', `The app declares no entity type \"${typeId}\".`)\n return entity\n }\n\n async function data(req: IncomingMessage, res: ServerResponse, url: URL, parts: string[]): Promise<void> {\n const [typeId, second] = parts\n if (!typeId || parts.length > 2) notFound()\n const target: Target = { entity: entityOf(typeId), auth: readAuth(root), caller: { principal: principalOf(req) } }\n const params = url.searchParams\n if (second === undefined) {\n if (req.method === 'GET') {\n sendJson(res, 200, records.list(target, params))\n return\n }\n if (req.method === 'POST') {\n const record = records.create(target, await readJsonObject(req))\n sendJson(res, 201, { id: record.id, data: record })\n return\n }\n methodNotAllowed()\n }\n if (second === 'count' || second === 'aggregate') {\n if (req.method !== 'GET') methodNotAllowed()\n sendJson(res, 200, records.aggregate(target, params, second === 'count'))\n return\n }\n if (req.method === 'GET') {\n const record = records.read(target, second)\n sendJson(res, 200, { id: record.id, data: record })\n return\n }\n if (req.method === 'PATCH') {\n const record = records.update(target, second, await readJsonObject(req))\n sendJson(res, 200, { id: record.id, data: record })\n return\n }\n if (req.method === 'DELETE') {\n records.remove(target, second)\n sendJson(res, 200, { data: { id: second, deleted: true } })\n return\n }\n methodNotAllowed()\n }\n\n // ------------------------------------------------------------------- pages\n\n function receiptFor(key: string, base: string): Record<string, unknown> | undefined {\n const receipt = readReceipt(root, key)\n if (!receipt) return undefined\n return rewriteEntitySources(receipt, base, new Set(readEntities(root).map((e) => e.typeId)))\n }\n\n function surface(req: IncomingMessage, res: ServerResponse, parts: string[]): void {\n if (req.method !== 'GET') methodNotAllowed()\n const file = parts.length === 1 ? parts[0] : undefined\n if (!file || !file.endsWith('.receipt.json')) notFound()\n if (readAuth(root)?.required && !principalOf(req)) {\n throw new HostError(401, 'SIGN_IN_REQUIRED', 'Sign in to open this page.')\n }\n const receipt = receiptFor(file.slice(0, -'.receipt.json'.length), originOf(req) + prefix)\n if (!receipt) notFound()\n sendJson(res, 200, receipt)\n }\n\n // ------------------------------------------------------------------ router\n\n async function route(req: IncomingMessage, res: ServerResponse, url: URL, rest: string): Promise<void> {\n const [head, ...tail] = segments(rest)\n switch (head) {\n case 'login':\n case 'register':\n case 'logout':\n case 'session':\n if (tail.length > 0) notFound()\n return door(req, res, head)\n case '_auth':\n return gateway(req, res, url, tail)\n case 'oidc':\n return oidc(req, res, url, tail)\n case 'records':\n return data(req, res, url, tail)\n case 'surfaces':\n return surface(req, res, tail)\n default:\n notFound()\n }\n }\n\n return {\n envelopeEntries(origin: string): Readonly<Record<string, unknown>> {\n const base = origin.replace(/\\/+$/, '') + prefix\n const out: Record<string, unknown> = {}\n const auth = authAddresses(readAuth(root), base)\n if (auth) out['auth.json'] = auth\n for (const key of surfaceKeys(root)) {\n const receipt = receiptFor(key, base)\n if (receipt) out[`surfaces/${key}.receipt.json`] = receipt\n }\n return out\n },\n\n async handle(req: IncomingMessage, res: ServerResponse): Promise<boolean> {\n let url: URL\n try {\n url = new URL(req.url ?? '/', 'http://localhost')\n } catch {\n return false\n }\n const path = url.pathname\n if (path !== prefix && !path.startsWith(`${prefix}/`)) return false\n try {\n await route(req, res, url, path.slice(prefix.length))\n } catch (err) {\n if (res.headersSent) {\n res.end()\n } else if (err instanceof HostError) {\n sendError(res, err)\n } else {\n // A broken definition file is the developer's to fix; say which.\n sendError(res, new HostError(500, 'HOST_ERROR', err instanceof Error ? err.message : String(err)))\n }\n }\n return true\n },\n\n reset(): void {\n records.reset()\n bearer.clear()\n transactions.clear()\n issuer.reset()\n },\n }\n}\n\nfunction withAuthError(returnTo: string, code: string): string {\n const [path, hash] = splitHash(returnTo)\n return `${path}${path.includes('?') ? '&' : '?'}auth_error=${encodeURIComponent(code)}${hash}`\n}\n\nfunction splitHash(value: string): [string, string] {\n const at = value.indexOf('#')\n return at === -1 ? [value, ''] : [value.slice(0, at), value.slice(at)]\n}\n"]}
1
+ {"version":3,"file":"local-host.js","sourceRoot":"","sources":["../../src/host/local-host.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoCG;AAGH,OAAO,EACL,SAAS,EACT,SAAS,EACT,YAAY,EACZ,cAAc,EACd,QAAQ,EACR,YAAY,EACZ,SAAS,EACT,QAAQ,GACT,MAAM,WAAW,CAAA;AAClB,OAAO,EACL,QAAQ,EACR,YAAY,EACZ,WAAW,EACX,WAAW,GAGZ,MAAM,kBAAkB,CAAA;AACzB,OAAO,EAAE,WAAW,EAAe,MAAM,cAAc,CAAA;AACvD,OAAO,EAAE,oBAAoB,EAAE,MAAM,eAAe,CAAA;AACpD,OAAO,EAAE,SAAS,EAAc,MAAM,WAAW,CAAA;AACjD,OAAO,EAAE,UAAU,EAAkB,MAAM,aAAa,CAAA;AAGxD,MAAM,CAAC,MAAM,gBAAgB,GAAG,EAAE,EAAE,EAAE,UAAU,EAAE,IAAI,EAAE,WAAW,EAAE,KAAK,EAAE,eAAe,EAAW,CAAA;AAEtG,qEAAqE;AACrE,MAAM,CAAC,MAAM,cAAc,GAAG,iBAAiB,CAAA;AAE/C,MAAM,cAAc,GAAG,CAAC,GAAG,QAAQ,CAAA;AACnC,MAAM,kBAAkB,GAAG,CAAC,GAAG,MAAM,CAAA;AAErC,kGAAkG;AAClG,MAAM,gBAAgB,GAAG,IAAI,GAAG,CAAC,CAAC,SAAS,EAAE,QAAQ,EAAE,QAAQ,EAAE,WAAW,CAAC,CAAC,CAAA;AAE9E,SAAS,eAAe,CAAC,MAAc;IACrC,MAAM,OAAO,GAAG,MAAM,CAAC,OAAO,CAAC,YAAY,EAAE,EAAE,CAAC,CAAA;IAChD,IAAI,CAAC,OAAO;QAAE,MAAM,IAAI,KAAK,CAAC,yDAAyD,CAAC,CAAA;IACxF,OAAO,IAAI,OAAO,EAAE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AO,GAAG,IAAI,GAAG,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,GAAG,cAAc,kBAAkB,CAAC,IAAI,CAAC,GAAG,IAAI,EAAE,CAAA;AAChG,CAAC;AAED,SAAS,SAAS,CAAC,KAAa;IAC9B,MAAM,EAAE,GAAG,KAAK,CAAC,OAAO,CAAC,GAAG,CAAC,CAAA;IAC7B,OAAO,EAAE,KAAK,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,EAAE,KAAK,CAAC,KAAK,CAAC,EAAE,CAAC,CAAC,CAAA;AACxE,CAAC","sourcesContent":["/**\n * The local host — the session protocol and the data protocol, in process,\n * for development.\n *\n * NOT A PRODUCTION SERVER. Records live in memory and vanish on restart; no\n * password is checked (the development e-mail is the development user, any\n * other e-mail a plain member); the issuer stand-in mints\n * unsigned ID tokens; there is no rate limit, no CORS, no TLS. It exists so an\n * app that declares data and sign-in runs on a laptop with no hosted service,\n * and so the runner's sign-in wall, account control, gate and data paths are\n * exercised against the same addresses and answers a session server gives.\n *\n * Everything is mounted under `prefix` (e.g. `/_host`); `<base>` below is\n * `<origin><prefix>`, which is also the app's own API base the runner derives\n * from `loginUrl` (session-protocol §2).\n *\n * App door (session-protocol §4, §8)\n * POST <base>/login, <base>/register any credentials → the development user\n * POST <base>/logout revokes the presented token\n * GET <base>/session the principal behind the token\n * GET <base>/_auth/start/<method> provider sign-in, through the same redirects\n * GET <base>/_auth/callback/<method> …ends here: HttpOnly cookie, back to returnTo\n * GET <base>/_auth/session the cookie's session (needs x-pwapp-request: 1)\n * POST <base>/_auth/logout deletes the cookie (needs x-pwapp-request: 1)\n * External issuer stand-in (session-protocol §3) — see ./oidc.ts\n * GET <base>/oidc/.well-known/openid-configuration, GET <base>/oidc/authorize,\n * POST <base>/oidc/token\n * Records (data-protocol §5) — see ./records.ts\n * GET|POST <base>/records/<T>, GET <base>/records/<T>/count, GET <base>/records/<T>/aggregate,\n * GET|PATCH|DELETE <base>/records/<T>/<id>\n * Pages\n * GET <base>/surfaces/<key>.receipt.json the receipt, entity sources rewritten to <base>,\n * refused without a session when sign-in is required\n *\n * Every credential is accepted on `x-app-session` or `Authorization: Bearer`.\n * Tokens are opaque and random, kept only as hashes, and never logged.\n */\n\nimport type { IncomingMessage, ServerResponse } from 'node:http'\nimport {\n HostError,\n cookiesOf,\n credentialOf,\n readJsonObject,\n redirect,\n safeReturnTo,\n sendError,\n sendJson,\n} from './http.js'\nimport {\n readAuth,\n readEntities,\n readReceipt,\n surfaceKeys,\n type AuthDeclaration,\n type EntityDeclaration,\n} from './definitions.js'\nimport { RecordStore, type Target } from './records.js'\nimport { rewriteEntitySources } from './receipts.js'\nimport { DevIssuer, type Grant } from './oidc.js'\nimport { TokenStore, type Principal } from './tokens.js'\nimport type { CreateLocalHost, LocalHost, LocalHostOptions } from './types.js'\n\nexport const DEFAULT_DEV_USER = { id: 'dev-user', name: 'Developer', email: 'dev@localhost' } as const\n\n/** The cookie the provider round trip leaves on the app's origin. */\nexport const SESSION_COOKIE = 'pwf_dev_session'\n\nconst SESSION_TTL_MS = 8 * 3600_000\nconst TRANSACTION_TTL_MS = 5 * 60_000\n\n/** The provider buttons a session server can name (envelope `auth.json` `providers[].method`). */\nconst PROVIDER_METHODS = new Set(['phiwebs', 'google', 'github', 'microsoft'])\n\nfunction normalisePrefix(prefix: string): string {\n const trimmed = prefix.replace(/^\\/+|\\/+$/g, '')\n if (!trimmed) throw new Error('createLocalHost: prefix must name a path, e.g. \"/_host\"')\n return `/${trimmed}`\n}\n\nfunction providersOf(auth: AuthDeclaration): string[] {\n return auth.methods.filter((m) => PROVIDER_METHODS.has(m))\n}\n\n/**\n * The envelope `auth.json` for this declaration, pointed at `base` — the\n * same shape a publisher writes (session-protocol §2), or `undefined` when the\n * app has no way in.\n *\n * - `external`: `oauth2-pkce` against the local issuer stand-in, keeping the\n * declared client id, scopes (plus `offline_access`, which is what makes a\n * refresh token exist) and audience.\n * - `app`: the password door when `password` is declared; the provider\n * buttons and the start address for every declared provider method; the\n * gateway's session and logout addresses for either; `methods` as declared.\n * - Either: `apiBase`, the base itself — where the app's records live, and\n * the only address the runner sends the visitor's session to.\n */\nexport function authAddresses(auth: AuthDeclaration | undefined, base: string): Record<string, unknown> | undefined {\n if (!auth) return undefined\n if (auth.topology === 'external') {\n if (!auth.issuer) return undefined\n const scopes = auth.issuer.scopes.includes('offline_access')\n ? [...auth.issuer.scopes]\n : [...auth.issuer.scopes, 'offline_access']\n return {\n provider: 'oauth2-pkce',\n apiBase: base,\n issuer: `${base}/oidc`,\n clientId: auth.issuer.clientId,\n scopes,\n ...(auth.issuer.audience ? { audience: auth.issuer.audience } : {}),\n }\n }\n const door: Record<string, unknown> = {}\n if (auth.methods.includes('password')) {\n door.provider = 'password'\n door.loginUrl = `${base}/login`\n door.registerUrl = `${base}/register`\n door.logoutUrl = `${base}/logout`\n door.sessionUrl = `${base}/session`\n }\n const providers = providersOf(auth)\n if (providers.length > 0) {\n door.provider = door.provider ?? 'platform'\n door.providers = providers.map((method) => ({ method }))\n door.startUrl = `${base}/_auth/start`\n door.gatewaySessionUrl = `${base}/_auth/session`\n door.gatewayLogoutUrl = `${base}/_auth/logout`\n }\n if (Object.keys(door).length === 0) return undefined\n // The runner asks the gateway on every app door, not only a provider one:\n // for a stored-nothing session on boot, and on every sign-out (it falls back\n // to `/_auth/session` and `/_auth/logout` at the page's origin, which on\n // `pwf dev` are not the host's). The host answers both under its base.\n door.gatewaySessionUrl ??= `${base}/_auth/session`\n door.gatewayLogoutUrl ??= `${base}/_auth/logout`\n door.methods = [...auth.methods]\n // Stated, not left for the runner to infer: every door reaches the same\n // records, and the runner sends the visitor's session to this base only.\n door.apiBase = base\n return door\n}\n\nfunction segments(rest: string): string[] {\n try {\n return rest.split('/').filter(Boolean).map((s) => decodeURIComponent(s))\n } catch {\n throw new HostError(400, 'INVALID_PATH', 'The path is not valid percent-encoding.')\n }\n}\n\nfunction methodNotAllowed(): never {\n throw new HostError(405, 'METHOD_NOT_ALLOWED', 'This route does not take that method.')\n}\n\nfunction notFound(): never {\n throw new HostError(404, 'NOT_FOUND', 'No such route on the local host.')\n}\n\nexport const createLocalHost: CreateLocalHost = (options: LocalHostOptions): LocalHost => {\n const root = options.root\n const prefix = normalisePrefix(options.prefix)\n const user: Principal = {\n id: options.user?.id ?? DEFAULT_DEV_USER.id,\n email: options.user?.email ?? DEFAULT_DEV_USER.email,\n displayName: options.user?.name ?? DEFAULT_DEV_USER.name,\n }\n\n const bearer = new TokenStore<Grant>()\n const transactions = new TokenStore<{ readonly returnTo: string; readonly method: string; readonly expiresAt: number }>()\n const records = new RecordStore(root, user)\n const issuer = new DevIssuer(bearer, user)\n\n const originOf = (req: IncomingMessage): string => `http://${req.headers.host ?? 'localhost'}`\n\n const principalOf = (req: IncomingMessage): Principal | undefined => bearer.get(credentialOf(req))?.principal\n\n function startSession(principal: Principal = user): { token: string; expiresAt: string; principal: Principal } {\n const expiresAt = Date.now() + SESSION_TTL_MS\n const token = bearer.issue({ principal, kind: 'session', expiresAt })\n return { token, expiresAt: new Date(expiresAt).toISOString(), principal }\n }\n\n /** The password door signs in whoever it is told: the development user, or a plain member for any other e-mail. */\n function principalNamed(email: unknown): Principal {\n if (typeof email !== 'string' || !email.trim() || email.trim().toLowerCase() === user.email.toLowerCase()) return user\n const address = email.trim().toLowerCase()\n return { id: `dev-${address}`, email: address, displayName: address }\n }\n\n const sessionCookie = (token: string, maxAgeS: number): string =>\n `${SESSION_COOKIE}=${encodeURIComponent(token)}; Path=${prefix}/_auth; HttpOnly; SameSite=Lax; Max-Age=${maxAgeS}`\n\n function requireRunnerRequest(req: IncomingMessage): void {\n if (req.headers['x-pwapp-request'] !== '1') {\n throw new HostError(403, 'RUNNER_REQUEST_REQUIRED', 'This address answers only the runner (x-pwapp-request: 1).')\n }\n }\n\n // ---------------------------------------------------------------- app door\n\n async function door(req: IncomingMessage, res: ServerResponse, action: string): Promise<void> {\n const auth = readAuth(root)\n if (action === 'session') {\n if (req.method !== 'GET') methodNotAllowed()\n const presented = credentialOf(req)\n const grant = bearer.get(presented)\n if (grant) {\n sendJson(res, 200, { data: { principal: grant.principal } })\n return\n }\n if (presented !== undefined || auth?.required) {\n throw new HostError(401, 'SIGN_IN_REQUIRED', 'No live session.')\n }\n sendJson(res, 200, { data: { principal: null } })\n return\n }\n if (req.method !== 'POST') methodNotAllowed()\n if (action === 'logout') {\n bearer.revoke(credentialOf(req))\n sendJson(res, 200, { data: { signedOut: true } })\n return\n }\n // login / register: the password is not checked. The e-mail picks who\n // signs in (see principalNamed), so access rules can be tried as a member.\n const credentials = await readJsonObject(req)\n if (!auth || auth.topology !== 'app' || !auth.methods.includes('password')) {\n throw new HostError(404, 'NO_PASSWORD_DOOR', 'This app declares no password sign-in.')\n }\n sendJson(res, action === 'register' ? 201 : 200, { data: startSession(principalNamed(credentials.email)) })\n }\n\n function gateway(req: IncomingMessage, res: ServerResponse, url: URL, parts: string[]): void {\n const [action, method] = parts\n if (action === 'start' || action === 'callback') {\n if (req.method !== 'GET') methodNotAllowed()\n if (parts.length !== 2 || !method) notFound()\n if (action === 'start') {\n const returnTo = safeReturnTo(url.searchParams.get('returnTo'))\n const auth = readAuth(root)\n if (!auth || auth.topology !== 'app' || !providersOf(auth).includes(method)) {\n redirect(res, withAuthError(returnTo, 'provider_unavailable'))\n return\n }\n // The provider's own leg is played by the callback below: the browser\n // still leaves the app, comes back to the callback, and lands on returnTo.\n const tx = transactions.issue({ returnTo, method, expiresAt: Date.now() + TRANSACTION_TTL_MS })\n redirect(res, `${prefix}/_auth/callback/${encodeURIComponent(method)}?tx=${encodeURIComponent(tx)}`)\n return\n }\n const tx = transactions.take(url.searchParams.get('tx') ?? undefined)\n if (!tx || tx.method !== method) {\n redirect(res, withAuthError('/', 'invalid_transaction'))\n return\n }\n const session = startSession()\n redirect(res, tx.returnTo, [sessionCookie(session.token, SESSION_TTL_MS / 1000)])\n return\n }\n if (parts.length !== 1) notFound()\n if (action === 'session') {\n if (req.method !== 'GET') methodNotAllowed()\n requireRunnerRequest(req)\n const token = cookiesOf(req)[SESSION_COOKIE]\n const grant = bearer.get(token)\n if (!token || !grant || grant.kind !== 'session') {\n throw new HostError(401, 'SIGN_IN_REQUIRED', 'No session cookie.')\n }\n sendJson(res, 200, {\n data: { token, expiresAt: new Date(grant.expiresAt).toISOString(), principal: grant.principal },\n })\n return\n }\n if (action === 'logout') {\n if (req.method !== 'POST') methodNotAllowed()\n requireRunnerRequest(req)\n bearer.revoke(cookiesOf(req)[SESSION_COOKIE])\n sendJson(res, 200, { data: { signedOut: true } }, { 'set-cookie': sessionCookie('', 0) })\n return\n }\n notFound()\n }\n\n // ------------------------------------------------------------------ issuer\n\n async function oidc(req: IncomingMessage, res: ServerResponse, url: URL, parts: string[]): Promise<void> {\n const auth = readAuth(root)\n if (!auth || auth.topology !== 'external' || !auth.issuer) {\n throw new HostError(404, 'NO_ISSUER', 'This app declares no external issuer.')\n }\n const iss = DevIssuer.issuerUrl(originOf(req), prefix)\n const route = parts.join('/')\n if (route === '.well-known/openid-configuration') {\n if (req.method !== 'GET') methodNotAllowed()\n issuer.discovery(res, iss)\n return\n }\n if (route === 'authorize') {\n if (req.method !== 'GET') methodNotAllowed()\n issuer.authorize(req, res, url, auth)\n return\n }\n if (route === 'token') {\n if (req.method !== 'POST') methodNotAllowed()\n await issuer.token(req, res, iss, auth)\n return\n }\n notFound()\n }\n\n // ----------------------------------------------------------------- records\n\n function entityOf(typeId: string): EntityDeclaration {\n const entity = readEntities(root).find((e) => e.typeId === typeId)\n if (!entity) throw new HostError(404, 'UNKNOWN_ENTITY_TYPE', `The app declares no entity type \"${typeId}\".`)\n return entity\n }\n\n async function data(req: IncomingMessage, res: ServerResponse, url: URL, parts: string[]): Promise<void> {\n const [typeId, second] = parts\n if (!typeId || parts.length > 2) notFound()\n const target: Target = { entity: entityOf(typeId), auth: readAuth(root), caller: { principal: principalOf(req) } }\n const params = url.searchParams\n if (second === undefined) {\n if (req.method === 'GET') {\n sendJson(res, 200, records.list(target, params))\n return\n }\n if (req.method === 'POST') {\n const record = records.create(target, await readJsonObject(req))\n sendJson(res, 201, { id: record.id, data: record })\n return\n }\n methodNotAllowed()\n }\n if (second === 'count' || second === 'aggregate') {\n if (req.method !== 'GET') methodNotAllowed()\n sendJson(res, 200, records.aggregate(target, params, second === 'count'))\n return\n }\n if (req.method === 'GET') {\n const record = records.read(target, second)\n sendJson(res, 200, { id: record.id, data: record })\n return\n }\n if (req.method === 'PATCH') {\n const record = records.update(target, second, await readJsonObject(req))\n sendJson(res, 200, { id: record.id, data: record })\n return\n }\n if (req.method === 'DELETE') {\n records.remove(target, second)\n sendJson(res, 200, { data: { id: second, deleted: true } })\n return\n }\n methodNotAllowed()\n }\n\n // ------------------------------------------------------------------- pages\n\n function receiptFor(key: string, base: string): Record<string, unknown> | undefined {\n const receipt = readReceipt(root, key)\n if (!receipt) return undefined\n return rewriteEntitySources(receipt, base, new Set(readEntities(root).map((e) => e.typeId)))\n }\n\n function surface(req: IncomingMessage, res: ServerResponse, parts: string[]): void {\n if (req.method !== 'GET') methodNotAllowed()\n const file = parts.length === 1 ? parts[0] : undefined\n if (!file || !file.endsWith('.receipt.json')) notFound()\n if (readAuth(root)?.required && !principalOf(req)) {\n throw new HostError(401, 'SIGN_IN_REQUIRED', 'Sign in to open this page.')\n }\n const receipt = receiptFor(file.slice(0, -'.receipt.json'.length), originOf(req) + prefix)\n if (!receipt) notFound()\n sendJson(res, 200, receipt)\n }\n\n // ------------------------------------------------------------------ router\n\n async function route(req: IncomingMessage, res: ServerResponse, url: URL, rest: string): Promise<void> {\n const [head, ...tail] = segments(rest)\n switch (head) {\n case 'login':\n case 'register':\n case 'logout':\n case 'session':\n if (tail.length > 0) notFound()\n return door(req, res, head)\n case '_auth':\n return gateway(req, res, url, tail)\n case 'oidc':\n return oidc(req, res, url, tail)\n case 'records':\n return data(req, res, url, tail)\n case 'surfaces':\n return surface(req, res, tail)\n default:\n notFound()\n }\n }\n\n return {\n envelopeEntries(origin: string): Readonly<Record<string, unknown>> {\n const base = origin.replace(/\\/+$/, '') + prefix\n const out: Record<string, unknown> = {}\n const auth = authAddresses(readAuth(root), base)\n if (auth) out['auth.json'] = auth\n for (const key of surfaceKeys(root)) {\n const receipt = receiptFor(key, base)\n if (receipt) out[`surfaces/${key}.receipt.json`] = receipt\n }\n return out\n },\n\n async handle(req: IncomingMessage, res: ServerResponse): Promise<boolean> {\n let url: URL\n try {\n url = new URL(req.url ?? '/', 'http://localhost')\n } catch {\n return false\n }\n const path = url.pathname\n if (path !== prefix && !path.startsWith(`${prefix}/`)) return false\n try {\n await route(req, res, url, path.slice(prefix.length))\n } catch (err) {\n if (res.headersSent) {\n res.end()\n } else if (err instanceof HostError) {\n sendError(res, err)\n } else {\n // A broken definition file is the developer's to fix; say which.\n sendError(res, new HostError(500, 'HOST_ERROR', err instanceof Error ? err.message : String(err)))\n }\n }\n return true\n },\n\n reset(): void {\n records.reset()\n bearer.clear()\n transactions.clear()\n issuer.reset()\n },\n }\n}\n\nfunction withAuthError(returnTo: string, code: string): string {\n const [path, hash] = splitHash(returnTo)\n return `${path}${path.includes('?') ? '&' : '?'}auth_error=${encodeURIComponent(code)}${hash}`\n}\n\nfunction splitHash(value: string): [string, string] {\n const at = value.indexOf('#')\n return at === -1 ? [value, ''] : [value.slice(0, at), value.slice(at)]\n}\n"]}
@@ -2,30 +2,53 @@
2
2
  * The app's own records, in memory (data-protocol §5).
3
3
  *
4
4
  * One collection per entity type declared in `app/definitions/entities.json`,
5
- * seeded on first use from `app/data/` (see `readSeed`). A record is
6
- * `{ …fields, id, entityType, createdAt, updatedAt }`, fields spread at the
7
- * top level like the reference server's.
5
+ * seeded on first use from `app/content/` then `app/data/` (see `readSeed`). A
6
+ * record is `{ …fields, id, entityType, createdAt, updatedAt }`, fields spread
7
+ * at the top level like the reference server's.
8
8
  *
9
- * ACCESS, read off the declarations — a deliberately small version of what a
10
- * hosted session server decides:
9
+ * ACCESS is the app's `auth.json` `access.rules` (definitions, `access`):
11
10
  *
12
- * - `auth.json` `required: true`: every data request needs a session
13
- * (`401 SIGN_IN_REQUIRED`).
14
- * - A collection is OWNER-SCOPED when an `access.rules[]` entry names it and
15
- * is not a public read grant (subject `public`/`anyone`/`visitors`/…, a
16
- * rule that grants reading and does not say "own"), when the entity
17
- * declares an owner field (`owner`, `ownerId`, `userId`, `createdBy`, …),
18
- * or when the entity carries `"scope": "owner"`. An owner-scoped collection
19
- * needs a session, lists only the caller's rows, and answers another
20
- * visitor's row as `404`.
21
- * - Every other collection is shared by the whole app: anyone may read and
22
- * write it.
11
+ * - `required: true`: every data request needs a session (`401`).
12
+ * - With no rule at all, every model is open to every visitor; once the app
13
+ * declares a rule, a model no rule names is closed.
14
+ * - A `count` grant answers the plain, unfiltered `/count` only.
15
+ * - A model some rule names is closed: a request passes when a rule whose
16
+ * subject matches the caller (`public`, `member`, or one of the caller's
17
+ * roles) grants its verb. `own` limits the grant to the caller's records.
18
+ * - Refused: `401 SIGN_IN_REQUIRED` without a session, `403 FORBIDDEN` with
19
+ * one; a record outside an `own` grant is `404`.
20
+ *
21
+ * The development user carries every role `access.roles` declares, so the
22
+ * author can try the app as staff; any other e-mail signs in as a plain member.
23
23
  */
24
24
  import { type AuthDeclaration, type EntityDeclaration } from './definitions.js';
25
25
  import { type AggregateResult, type Row } from './query.js';
26
26
  import type { Principal } from './tokens.js';
27
27
  export type Scope = 'project' | 'owner';
28
- export declare function scopeOf(entity: EntityDeclaration, auth: AuthDeclaration | undefined): Scope;
28
+ /** The verbs a rule grants (`read` and `write` expand to these). */
29
+ export type AccessVerb = 'create' | 'list' | 'view' | 'update' | 'delete' | 'count';
30
+ /** What one verb allows the caller: nothing, their own records, or every record. */
31
+ export type AccessReach = 'none' | 'own' | 'all';
32
+ type Verb = AccessVerb;
33
+ type Reach = AccessReach;
34
+ export type Access = Readonly<Record<Verb, Reach>>;
35
+ /** The words of a rule: verbs and `own`; anything else is ignored. */
36
+ export declare function parseRule(rule: string): {
37
+ verbs: Verb[];
38
+ own: boolean;
39
+ unknown: string[];
40
+ };
41
+ /**
42
+ * What `caller` (with `roles`) may do with `entity` under the app's rules.
43
+ *
44
+ * An app that declares no access rule at all leaves every model open. Once it
45
+ * declares one, a model no rule names is closed: nobody listed it, so nobody
46
+ * was granted it (a collection only a receipt reads must be named to be read).
47
+ */
48
+ export declare function accessOf(entity: EntityDeclaration, auth: AuthDeclaration | undefined, caller: {
49
+ readonly principal: Principal | undefined;
50
+ readonly roles: readonly string[];
51
+ }): Access;
29
52
  export interface Caller {
30
53
  readonly principal: Principal | undefined;
31
54
  }
@@ -58,12 +81,19 @@ export declare class RecordStore {
58
81
  constructor(root: string, devUser: Principal);
59
82
  reset(): void;
60
83
  private collection;
61
- /** Refuses a caller the declarations do not let in; answers the collection's scope. */
62
- private guard;
63
- /** The rows this caller may see, newest change first, after `filter`. */
64
- private visible;
84
+ /** What the caller may do here; refuses a caller the app does not let in at all. */
85
+ private access;
86
+ /** The reach of `verb`, refusing when it is none. */
87
+ private allow;
88
+ /** The rows within `reach`, newest change first, after `filter`. */
89
+ private rows;
65
90
  list(target: Target, params: URLSearchParams): ListAnswer;
66
- /** `/count` (`plainCount`) or `/aggregate?fn&field`. */
91
+ /**
92
+ * `/count` (`plainCount`) or `/aggregate?fn&field`, over the rows `list`
93
+ * reaches. A caller whose only grant is `count` gets the plain, unfiltered
94
+ * count over every row and nothing more: a filter or a sum would read field
95
+ * values out of rows they may not list, one number at a time.
96
+ */
67
97
  aggregate(target: Target, params: URLSearchParams, plainCount: boolean): AggregateAnswer;
68
98
  private find;
69
99
  read(target: Target, id: string): Row;
@@ -71,3 +101,4 @@ export declare class RecordStore {
71
101
  update(target: Target, id: string, body: Record<string, unknown>): Row;
72
102
  remove(target: Target, id: string): void;
73
103
  }
104
+ export {};
@@ -2,45 +2,43 @@
2
2
  * The app's own records, in memory (data-protocol §5).
3
3
  *
4
4
  * One collection per entity type declared in `app/definitions/entities.json`,
5
- * seeded on first use from `app/data/` (see `readSeed`). A record is
6
- * `{ …fields, id, entityType, createdAt, updatedAt }`, fields spread at the
7
- * top level like the reference server's.
5
+ * seeded on first use from `app/content/` then `app/data/` (see `readSeed`). A
6
+ * record is `{ …fields, id, entityType, createdAt, updatedAt }`, fields spread
7
+ * at the top level like the reference server's.
8
8
  *
9
- * ACCESS, read off the declarations — a deliberately small version of what a
10
- * hosted session server decides:
9
+ * ACCESS is the app's `auth.json` `access.rules` (definitions, `access`):
11
10
  *
12
- * - `auth.json` `required: true`: every data request needs a session
13
- * (`401 SIGN_IN_REQUIRED`).
14
- * - A collection is OWNER-SCOPED when an `access.rules[]` entry names it and
15
- * is not a public read grant (subject `public`/`anyone`/`visitors`/…, a
16
- * rule that grants reading and does not say "own"), when the entity
17
- * declares an owner field (`owner`, `ownerId`, `userId`, `createdBy`, …),
18
- * or when the entity carries `"scope": "owner"`. An owner-scoped collection
19
- * needs a session, lists only the caller's rows, and answers another
20
- * visitor's row as `404`.
21
- * - Every other collection is shared by the whole app: anyone may read and
22
- * write it.
11
+ * - `required: true`: every data request needs a session (`401`).
12
+ * - With no rule at all, every model is open to every visitor; once the app
13
+ * declares a rule, a model no rule names is closed.
14
+ * - A `count` grant answers the plain, unfiltered `/count` only.
15
+ * - A model some rule names is closed: a request passes when a rule whose
16
+ * subject matches the caller (`public`, `member`, or one of the caller's
17
+ * roles) grants its verb. `own` limits the grant to the caller's records.
18
+ * - Refused: `401 SIGN_IN_REQUIRED` without a session, `403 FORBIDDEN` with
19
+ * one; a record outside an `own` grant is `404`.
20
+ *
21
+ * The development user carries every role `access.roles` declares, so the
22
+ * author can try the app as staff; any other e-mail signs in as a plain member.
23
23
  */
24
24
  import { randomUUID } from 'node:crypto';
25
25
  import { HostError } from './http.js';
26
26
  import { readSeed } from './definitions.js';
27
27
  import { aggregate, matches, parseFilter, parseSort, sortRows } from './query.js';
28
- const PUBLIC_SUBJECTS = new Set([
29
- 'public',
30
- 'anyone',
31
- 'anybody',
32
- 'everyone',
33
- 'everybody',
34
- 'all',
35
- 'visitor',
36
- 'visitors',
37
- 'guest',
38
- 'guests',
39
- 'anonymous',
40
- '*',
41
- ]);
42
- const READ_VERB = /\b(read|reads|see|sees|view|views|list|lists|browse|browses)\b/i;
43
- const OWN_WORD = /\b(own|their|his|her|only)\b/i;
28
+ const VERBS = {
29
+ create: ['create'],
30
+ list: ['list'],
31
+ view: ['view'],
32
+ update: ['update'],
33
+ delete: ['delete'],
34
+ count: ['count'],
35
+ read: ['list', 'view'],
36
+ write: ['create', 'update', 'delete'],
37
+ };
38
+ const OPEN = { create: 'all', list: 'all', view: 'all', update: 'all', delete: 'all', count: 'all' };
39
+ const CLOSED = { create: 'none', list: 'none', view: 'none', update: 'none', delete: 'none', count: 'none' };
40
+ const RANK = { none: 0, own: 1, all: 2 };
41
+ /** Fields a record names its owner in; a create fills the first one when blank. */
44
42
  const OWNER_FIELDS = new Set([
45
43
  'owner',
46
44
  'ownerid',
@@ -57,15 +55,52 @@ const norm = (s) => s.toLowerCase().replace(/[\s_-]/g, '');
57
55
  function ownerFieldOf(entity) {
58
56
  return entity.fields.find((f) => OWNER_FIELDS.has(norm(f.name)))?.name;
59
57
  }
60
- export function scopeOf(entity, auth) {
58
+ /** The words of a rule: verbs and `own`; anything else is ignored. */
59
+ export function parseRule(rule) {
60
+ const verbs = new Set();
61
+ const unknown = [];
62
+ let own = false;
63
+ for (const word of rule.toLowerCase().split(/[\s,]+/).filter(Boolean)) {
64
+ if (word === 'own')
65
+ own = true;
66
+ else if (VERBS[word])
67
+ for (const v of VERBS[word])
68
+ verbs.add(v);
69
+ else
70
+ unknown.push(word);
71
+ }
72
+ return { verbs: [...verbs], own, unknown };
73
+ }
74
+ /**
75
+ * What `caller` (with `roles`) may do with `entity` under the app's rules.
76
+ *
77
+ * An app that declares no access rule at all leaves every model open. Once it
78
+ * declares one, a model no rule names is closed: nobody listed it, so nobody
79
+ * was granted it (a collection only a receipt reads must be named to be read).
80
+ */
81
+ export function accessOf(entity, auth, caller) {
61
82
  const names = new Set([norm(entity.typeId), ...(entity.displayName ? [norm(entity.displayName)] : [])]);
62
- const rules = (auth?.access.rules ?? []).filter((r) => names.has(norm(r.model)));
63
- const publicGrant = rules.some((r) => PUBLIC_SUBJECTS.has(r.subject.trim().toLowerCase()) && READ_VERB.test(r.rule) && !OWN_WORD.test(r.rule));
64
- if (publicGrant)
65
- return 'project';
66
- if (rules.length > 0 || ownerFieldOf(entity) !== undefined || entity.scope === 'owner')
67
- return 'owner';
68
- return 'project';
83
+ const declared = auth?.access.rules ?? [];
84
+ if (declared.length === 0)
85
+ return OPEN;
86
+ const rules = declared.filter((r) => names.has(norm(r.model)));
87
+ if (rules.length === 0)
88
+ return CLOSED;
89
+ const access = { create: 'none', list: 'none', view: 'none', update: 'none', delete: 'none', count: 'none' };
90
+ for (const r of rules) {
91
+ const subject = r.subject.trim();
92
+ const applies = subject === 'public' || (caller.principal !== undefined && (subject === 'member' || caller.roles.includes(subject)));
93
+ if (!applies)
94
+ continue;
95
+ const { verbs, own } = parseRule(r.rule);
96
+ for (const verb of verbs) {
97
+ // A visitor who is not signed in owns no record; `own` never limits create.
98
+ const reach = !own || verb === 'create' ? 'all' : caller.principal ? 'own' : 'none';
99
+ if (RANK[reach] > RANK[access[verb]])
100
+ access[verb] = reach;
101
+ }
102
+ }
103
+ return access;
69
104
  }
70
105
  const isEmpty = (v) => v === undefined || v === null || v === '';
71
106
  export class RecordStore {
@@ -107,20 +142,26 @@ export class RecordStore {
107
142
  this.collections.set(entity.typeId, rows);
108
143
  return rows;
109
144
  }
110
- /** Refuses a caller the declarations do not let in; answers the collection's scope. */
111
- guard({ entity, auth, caller }) {
145
+ /** What the caller may do here; refuses a caller the app does not let in at all. */
146
+ access({ entity, auth, caller }) {
112
147
  if (auth?.required && !caller.principal) {
113
148
  throw new HostError(401, 'SIGN_IN_REQUIRED', 'Sign in to use this app.');
114
149
  }
115
- const scope = scopeOf(entity, auth);
116
- if (scope === 'owner' && !caller.principal) {
117
- throw new HostError(401, 'SIGN_IN_REQUIRED', `Sign in to see your ${entity.displayName ?? entity.typeId} records.`);
118
- }
119
- return scope;
150
+ const roles = caller.principal?.id === this.devUser.id ? (auth?.access.roles ?? []) : [];
151
+ return accessOf(entity, auth, { principal: caller.principal, roles });
120
152
  }
121
- /** The rows this caller may see, newest change first, after `filter`. */
122
- visible(target, params) {
123
- const scope = this.guard(target);
153
+ /** The reach of `verb`, refusing when it is none. */
154
+ allow(target, verb, access = this.access(target)) {
155
+ const reach = access[verb];
156
+ if (reach !== 'none')
157
+ return reach;
158
+ const name = target.entity.displayName ?? target.entity.typeId;
159
+ if (!target.caller.principal)
160
+ throw new HostError(401, 'SIGN_IN_REQUIRED', `Sign in to use ${name} records.`);
161
+ throw new HostError(403, 'FORBIDDEN', `You may not ${verb} ${name} records.`);
162
+ }
163
+ /** The rows within `reach`, newest change first, after `filter`. */
164
+ rows(target, reach, params) {
124
165
  let filter;
125
166
  try {
126
167
  filter = parseFilter(params.get('filter'));
@@ -129,13 +170,14 @@ export class RecordStore {
129
170
  throw new HostError(400, 'INVALID_QUERY', 'filter must be a JSON filter object.');
130
171
  }
131
172
  const rows = [...this.collection(target.entity).values()]
132
- .filter((s) => scope === 'project' || s.owner === target.caller.principal?.id)
173
+ .filter((s) => reach === 'all' || s.owner === target.caller.principal?.id)
133
174
  .sort((a, b) => b.touched - a.touched)
134
175
  .map((s) => s.record);
135
- return { scope, rows: filter ? rows.filter((r) => matches(r, filter)) : rows };
176
+ return filter ? rows.filter((r) => matches(r, filter)) : rows;
136
177
  }
137
178
  list(target, params) {
138
- const { scope, rows } = this.visible(target, params);
179
+ const reach = this.allow(target, 'list');
180
+ const rows = this.rows(target, reach, params);
139
181
  const sort = parseSort(params.get('sort'));
140
182
  const ordered = sort.length > 0 ? sortRows(rows, sort) : rows;
141
183
  const limitRaw = Number(params.get('limit') ?? '100');
@@ -144,10 +186,15 @@ export class RecordStore {
144
186
  const offset = Number.isFinite(offsetRaw) ? Math.max(0, Math.trunc(offsetRaw)) : 0;
145
187
  return {
146
188
  data: ordered.slice(offset, offset + limit),
147
- meta: { total: ordered.length, scope, timestamp: new Date().toISOString() },
189
+ meta: { total: ordered.length, scope: reach === 'own' ? 'owner' : 'project', timestamp: new Date().toISOString() },
148
190
  };
149
191
  }
150
- /** `/count` (`plainCount`) or `/aggregate?fn&field`. */
192
+ /**
193
+ * `/count` (`plainCount`) or `/aggregate?fn&field`, over the rows `list`
194
+ * reaches. A caller whose only grant is `count` gets the plain, unfiltered
195
+ * count over every row and nothing more: a filter or a sum would read field
196
+ * values out of rows they may not list, one number at a time.
197
+ */
151
198
  aggregate(target, params, plainCount) {
152
199
  const fn = plainCount ? 'count' : params.get('fn');
153
200
  if (fn !== 'count' && fn !== 'sum' && fn !== 'avg') {
@@ -156,26 +203,32 @@ export class RecordStore {
156
203
  const field = plainCount ? undefined : (params.get('field') ?? undefined);
157
204
  if (fn !== 'count' && !field)
158
205
  throw new HostError(400, 'INVALID_QUERY', `${fn} needs a field.`);
159
- const { scope, rows } = this.visible(target, params);
160
- return { data: aggregate(rows, fn, field), meta: { scope, timestamp: new Date().toISOString() } };
206
+ const access = this.access(target);
207
+ const bare = plainCount && params.get('filter') === null;
208
+ const reach = bare && access.count === 'all' ? 'all' : this.allow(target, 'list', access);
209
+ const rows = this.rows(target, reach, params);
210
+ return {
211
+ data: aggregate(rows, fn, field),
212
+ meta: { scope: reach === 'own' ? 'owner' : 'project', timestamp: new Date().toISOString() },
213
+ };
161
214
  }
162
- find(target, id) {
163
- const scope = this.guard(target);
215
+ find(target, verb, id) {
216
+ const reach = this.allow(target, verb);
164
217
  const stored = this.collection(target.entity).get(id);
165
- if (!stored || (scope === 'owner' && stored.owner !== target.caller.principal?.id)) {
218
+ if (!stored || (reach === 'own' && stored.owner !== target.caller.principal?.id)) {
166
219
  throw new HostError(404, 'NOT_FOUND', `No ${target.entity.typeId} record "${id}".`);
167
220
  }
168
221
  return stored;
169
222
  }
170
223
  read(target, id) {
171
- return this.find(target, id).record;
224
+ return this.find(target, 'view', id).record;
172
225
  }
173
226
  create(target, body) {
174
227
  const { entity, caller } = target;
175
- const scope = this.guard(target);
228
+ this.allow(target, 'create');
176
229
  const fields = writable(body);
177
230
  const ownerField = ownerFieldOf(entity);
178
- if (scope === 'owner' && ownerField && isEmpty(fields[ownerField]) && caller.principal) {
231
+ if (ownerField && isEmpty(fields[ownerField]) && caller.principal) {
179
232
  fields[ownerField] = caller.principal.id;
180
233
  }
181
234
  const missing = entity.fields.filter((f) => f.required && isEmpty(fields[f.name])).map((f) => f.name);
@@ -189,7 +242,7 @@ export class RecordStore {
189
242
  return record;
190
243
  }
191
244
  update(target, id, body) {
192
- const stored = this.find(target, id);
245
+ const stored = this.find(target, 'update', id);
193
246
  const fields = writable(body);
194
247
  const cleared = target.entity.fields
195
248
  .filter((f) => f.required && f.name in fields && isEmpty(fields[f.name]))
@@ -208,7 +261,7 @@ export class RecordStore {
208
261
  return stored.record;
209
262
  }
210
263
  remove(target, id) {
211
- this.find(target, id);
264
+ this.find(target, 'delete', id);
212
265
  this.collection(target.entity).delete(id);
213
266
  }
214
267
  }