@pwfabric/cli 1.0.0 → 1.1.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.
- package/README.md +4 -2
- package/dist/commands/dev.js +3 -2
- package/dist/commands/dev.js.map +1 -1
- package/dist/commands/lib/report.d.ts +15 -1
- package/dist/commands/lib/report.js +95 -3
- package/dist/commands/lib/report.js.map +1 -1
- package/dist/dev/envelope.d.ts +4 -1
- package/dist/dev/envelope.js +6 -1
- package/dist/dev/envelope.js.map +1 -1
- package/dist/dev/server.js +24 -10
- package/dist/dev/server.js.map +1 -1
- package/dist/host/definitions.d.ts +10 -10
- package/dist/host/definitions.js +26 -11
- package/dist/host/definitions.js.map +1 -1
- package/dist/host/local-host.d.ts +3 -2
- package/dist/host/local-host.js +17 -9
- package/dist/host/local-host.js.map +1 -1
- package/dist/host/records.d.ts +37 -22
- package/dist/host/records.js +99 -64
- package/dist/host/records.js.map +1 -1
- package/package.json +8 -8
|
@@ -4,7 +4,8 @@
|
|
|
4
4
|
* app/definitions/auth.json who may enter (definitions.md, `auth.json`)
|
|
5
5
|
* app/definitions/entities.json the collections the host keeps
|
|
6
6
|
* app/surfaces/<key>.receipt.json the pages it serves
|
|
7
|
-
* app/
|
|
7
|
+
* app/content/<typeId>.json the app's shipped records (data-protocol §6)
|
|
8
|
+
* app/data/<typeId>.jsonl | .json development records, never published
|
|
8
9
|
*
|
|
9
10
|
* Read on every call, never cached: `pwf dev` edits these files while the
|
|
10
11
|
* host runs, and a definition change must apply without a restart. An absent
|
|
@@ -22,6 +23,7 @@ export interface AuthDeclaration {
|
|
|
22
23
|
readonly audience?: string;
|
|
23
24
|
};
|
|
24
25
|
readonly access: {
|
|
26
|
+
readonly roles: readonly string[];
|
|
25
27
|
readonly rules: readonly {
|
|
26
28
|
readonly subject: string;
|
|
27
29
|
readonly model: string;
|
|
@@ -38,8 +40,6 @@ export interface EntityDeclaration {
|
|
|
38
40
|
readonly typeId: string;
|
|
39
41
|
readonly displayName?: string;
|
|
40
42
|
readonly fields: readonly EntityField[];
|
|
41
|
-
/** Carried member (not in the spec yet): `"owner"` makes the collection per-visitor. */
|
|
42
|
-
readonly scope?: string;
|
|
43
43
|
}
|
|
44
44
|
/** `undefined` when the app declares no `auth.json` (or an empty one). */
|
|
45
45
|
export declare function readAuth(root: string): AuthDeclaration | undefined;
|
|
@@ -49,13 +49,13 @@ export declare const PAGE_KEY: RegExp;
|
|
|
49
49
|
export declare function surfaceKeys(root: string): string[];
|
|
50
50
|
export declare function readReceipt(root: string, key: string): Record<string, unknown> | undefined;
|
|
51
51
|
/**
|
|
52
|
-
* Seed rows for one collection.
|
|
52
|
+
* Seed rows for one collection: the app's content, then its development data.
|
|
53
53
|
*
|
|
54
|
-
*
|
|
55
|
-
* `
|
|
56
|
-
*
|
|
57
|
-
*
|
|
58
|
-
*
|
|
59
|
-
*
|
|
54
|
+
* Two folders, one shape (data-protocol §6):
|
|
55
|
+
* - `app/content/<typeId>.json` — records the app ships for every visitor; a
|
|
56
|
+
* publisher inserts each one the record store does not hold yet.
|
|
57
|
+
* - `app/data/<typeId>.json` — development and test records; never published.
|
|
58
|
+
* A data row with the id of a content row replaces it here, so a developer can
|
|
59
|
+
* try a variant without editing the content.
|
|
60
60
|
*/
|
|
61
61
|
export declare function readSeed(root: string, typeId: string): Record<string, unknown>[];
|
package/dist/host/definitions.js
CHANGED
|
@@ -4,7 +4,8 @@
|
|
|
4
4
|
* app/definitions/auth.json who may enter (definitions.md, `auth.json`)
|
|
5
5
|
* app/definitions/entities.json the collections the host keeps
|
|
6
6
|
* app/surfaces/<key>.receipt.json the pages it serves
|
|
7
|
-
* app/
|
|
7
|
+
* app/content/<typeId>.json the app's shipped records (data-protocol §6)
|
|
8
|
+
* app/data/<typeId>.jsonl | .json development records, never published
|
|
8
9
|
*
|
|
9
10
|
* Read on every call, never cached: `pwf dev` edits these files while the
|
|
10
11
|
* host runs, and a definition change must apply without a restart. An absent
|
|
@@ -51,7 +52,7 @@ export function readAuth(root) {
|
|
|
51
52
|
},
|
|
52
53
|
}
|
|
53
54
|
: {}),
|
|
54
|
-
access: { rules },
|
|
55
|
+
access: { roles: strings(access.roles), rules },
|
|
55
56
|
};
|
|
56
57
|
}
|
|
57
58
|
export function readEntities(root) {
|
|
@@ -68,7 +69,6 @@ export function readEntities(root) {
|
|
|
68
69
|
typeId: e.typeId,
|
|
69
70
|
...(typeof e.displayName === 'string' ? { displayName: e.displayName } : {}),
|
|
70
71
|
fields,
|
|
71
|
-
...(typeof e.scope === 'string' ? { scope: e.scope } : {}),
|
|
72
72
|
},
|
|
73
73
|
];
|
|
74
74
|
});
|
|
@@ -92,19 +92,34 @@ export function readReceipt(root, key) {
|
|
|
92
92
|
return isObject(raw) ? raw : undefined;
|
|
93
93
|
}
|
|
94
94
|
/**
|
|
95
|
-
* Seed rows for one collection.
|
|
95
|
+
* Seed rows for one collection: the app's content, then its development data.
|
|
96
96
|
*
|
|
97
|
-
*
|
|
98
|
-
* `
|
|
99
|
-
*
|
|
100
|
-
*
|
|
101
|
-
*
|
|
102
|
-
*
|
|
97
|
+
* Two folders, one shape (data-protocol §6):
|
|
98
|
+
* - `app/content/<typeId>.json` — records the app ships for every visitor; a
|
|
99
|
+
* publisher inserts each one the record store does not hold yet.
|
|
100
|
+
* - `app/data/<typeId>.json` — development and test records; never published.
|
|
101
|
+
* A data row with the id of a content row replaces it here, so a developer can
|
|
102
|
+
* try a variant without editing the content.
|
|
103
103
|
*/
|
|
104
104
|
export function readSeed(root, typeId) {
|
|
105
105
|
if (!PAGE_KEY.test(typeId))
|
|
106
106
|
return [];
|
|
107
|
-
const
|
|
107
|
+
const rows = new Map();
|
|
108
|
+
let anonymous = 0;
|
|
109
|
+
for (const row of [...readRecordsFile(join(root, 'app', 'content'), typeId), ...readRecordsFile(join(root, 'app', 'data'), typeId)]) {
|
|
110
|
+
const id = typeof row.id === 'string' || typeof row.id === 'number' ? String(row.id) : `\0${anonymous++}`;
|
|
111
|
+
rows.set(id, row);
|
|
112
|
+
}
|
|
113
|
+
return [...rows.values()];
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* `<dir>/<typeId>.json` holding `{ "data": [ …records ] }` — the same `data`
|
|
117
|
+
* envelope a record list answer uses. A record may carry its own `id`;
|
|
118
|
+
* `createdAt`/`updatedAt` are filled when absent. Also accepted, for
|
|
119
|
+
* hand-written files only: `<dir>/<typeId>.jsonl`, one JSON object per line
|
|
120
|
+
* (blank lines skipped), read when no `.json` file exists.
|
|
121
|
+
*/
|
|
122
|
+
function readRecordsFile(dir, typeId) {
|
|
108
123
|
const jsonPath = join(dir, `${typeId}.json`);
|
|
109
124
|
const json = readJson(jsonPath);
|
|
110
125
|
if (json !== undefined) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"definitions.js","sourceRoot":"","sources":["../../src/host/definitions.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,SAAS,CAAA;AAC/D,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAA;AA+BhC,SAAS,QAAQ,CAAC,IAAY;IAC5B,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC;QAAE,OAAO,SAAS,CAAA;IACvC,MAAM,IAAI,GAAG,YAAY,CAAC,IAAI,EAAE,MAAM,CAAC,CAAA;IACvC,IAAI,CAAC;QACH,OAAO,IAAI,CAAC,KAAK,CAAC,IAAI,CAAY,CAAA;IACpC,CAAC;IAAC,OAAO,GAAG,EAAE,CAAC;QACb,MAAM,IAAI,KAAK,CAAC,GAAG,IAAI,uBAAwB,GAAa,CAAC,OAAO,EAAE,CAAC,CAAA;IACzE,CAAC;AACH,CAAC;AAED,MAAM,QAAQ,GAAG,CAAC,CAAU,EAAgC,EAAE,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,OAAO,CAAC,KAAK,QAAQ,IAAI,CAAC,KAAK,CAAC,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,CAAA;QACzE,OAAO,GAAG,CAAA;IACZ,CAAC,CAAC,CAAA;AACN,CAAC","sourcesContent":["/**\n * What the local host reads from the pwpack folder.\n *\n * app/definitions/auth.json who may enter (definitions.md, `auth.json`)\n * app/definitions/entities.json the collections the host keeps\n * app/surfaces/<key>.receipt.json the pages it serves\n * app/data/<typeId>.jsonl | .json seed rows (a convention of this host)\n *\n * Read on every call, never cached: `pwf dev` edits these files while the\n * host runs, and a definition change must apply without a restart. An absent\n * file is \"not declared\"; an unreadable one is reported as an error rather\n * than guessed around.\n */\n\nimport { existsSync, readdirSync, readFileSync } from 'node:fs'\nimport { join } from 'node:path'\n\nexport interface AuthDeclaration {\n readonly required: boolean\n readonly topology: 'app' | 'external'\n readonly methods: readonly string[]\n readonly issuer?: {\n readonly issuer: string\n readonly clientId: string\n readonly scopes: readonly string[]\n readonly audience?: string\n }\n readonly access: {\n readonly rules: readonly { readonly subject: string; readonly model: string; readonly rule: string }[]\n }\n}\n\nexport interface EntityField {\n readonly name: string\n readonly type: string\n readonly required: boolean\n}\n\nexport interface EntityDeclaration {\n readonly typeId: string\n readonly displayName?: string\n readonly fields: readonly EntityField[]\n /** Carried member (not in the spec yet): `\"owner\"` makes the collection per-visitor. */\n readonly scope?: string\n}\n\nfunction readJson(path: string): unknown {\n if (!existsSync(path)) return undefined\n const text = readFileSync(path, 'utf8')\n try {\n return JSON.parse(text) as unknown\n } catch (err) {\n throw new Error(`${path} is not valid JSON: ${(err as Error).message}`)\n }\n}\n\nconst isObject = (v: unknown): v is Record<string, unknown> => Boolean(v) && typeof v === 'object' && !Array.isArray(v)\nconst strings = (v: unknown): string[] => (Array.isArray(v) ? v.filter((x): x is string => typeof x === 'string') : [])\n\n/** `undefined` when the app declares no `auth.json` (or an empty one). */\nexport function readAuth(root: string): AuthDeclaration | undefined {\n const raw = readJson(join(root, 'app', 'definitions', 'auth.json'))\n if (!isObject(raw) || Object.keys(raw).length === 0) return undefined\n const topology = raw.topology === 'external' ? 'external' : 'app'\n const iss = isObject(raw.issuer) ? raw.issuer : undefined\n const access = isObject(raw.access) ? raw.access : {}\n const rules = (Array.isArray(access.rules) ? access.rules : [])\n .filter(isObject)\n .map((r) => ({ subject: String(r.subject ?? ''), model: String(r.model ?? ''), rule: String(r.rule ?? '') }))\n return {\n required: raw.required === true,\n topology,\n methods: strings(raw.methods),\n ...(iss && typeof iss.issuer === 'string' && typeof iss.clientId === 'string'\n ? {\n issuer: {\n issuer: iss.issuer,\n clientId: iss.clientId,\n scopes: Array.isArray(iss.scopes) ? strings(iss.scopes) : ['openid', 'profile', 'email'],\n ...(typeof iss.audience === 'string' && iss.audience ? { audience: iss.audience } : {}),\n },\n }\n : {}),\n access: { rules },\n }\n}\n\nexport function readEntities(root: string): EntityDeclaration[] {\n const raw = readJson(join(root, 'app', 'definitions', 'entities.json'))\n const list = isObject(raw) && Array.isArray(raw.entities) ? raw.entities : []\n return list.filter(isObject).flatMap((e) => {\n if (typeof e.typeId !== 'string' || !e.typeId) return []\n const fields = (Array.isArray(e.fields) ? e.fields : []).filter(isObject).flatMap((f) =>\n typeof f.name === 'string' && f.name\n ? [{ name: f.name, type: typeof f.type === 'string' ? f.type : 'text', required: f.required === true }]\n : []\n )\n return [\n {\n typeId: e.typeId,\n ...(typeof e.displayName === 'string' ? { displayName: e.displayName } : {}),\n fields,\n ...(typeof e.scope === 'string' ? { scope: e.scope } : {}),\n },\n ]\n })\n}\n\n/** A page key is a file name, never a path. */\nexport const PAGE_KEY = /^[A-Za-z0-9][A-Za-z0-9_-]*$/\n\nexport function surfaceKeys(root: string): string[] {\n const dir = join(root, 'app', 'surfaces')\n if (!existsSync(dir)) return []\n return readdirSync(dir)\n .filter((f) => f.endsWith('.receipt.json'))\n .map((f) => f.slice(0, -'.receipt.json'.length))\n .filter((k) => PAGE_KEY.test(k))\n .sort()\n}\n\nexport function readReceipt(root: string, key: string): Record<string, unknown> | undefined {\n if (!PAGE_KEY.test(key)) return undefined\n const raw = readJson(join(root, 'app', 'surfaces', `${key}.receipt.json`))\n return isObject(raw) ? raw : undefined\n}\n\n/**\n * Seed rows for one collection.\n *\n * THE CONVENTION (proposed for the spec): `app/data/<typeId>.json` holding\n * `{ \"data\": [ …records ] }` — the same `data` envelope a record list answer\n * uses. A record may carry its own `id`; `createdAt`/`updatedAt` are filled\n * when absent. Also accepted, for hand-written seed files only:\n * `app/data/<typeId>.jsonl`, one JSON object per line (blank lines skipped),\n * read when no `.json` file exists.\n */\nexport function readSeed(root: string, typeId: string): Record<string, unknown>[] {\n if (!PAGE_KEY.test(typeId)) return []\n const dir = join(root, 'app', 'data')\n const jsonPath = join(dir, `${typeId}.json`)\n const json = readJson(jsonPath)\n if (json !== undefined) {\n if (!isObject(json) || !Array.isArray(json.data)) {\n throw new Error(`${jsonPath} must be { \"data\": [ ...records ] }`)\n }\n return json.data.filter(isObject)\n }\n const jsonl = join(dir, `${typeId}.jsonl`)\n if (!existsSync(jsonl)) return []\n return readFileSync(jsonl, 'utf8')\n .split(/\\r?\\n/)\n .map((line, i) => [line.trim(), i + 1] as const)\n .filter(([line]) => line !== '')\n .map(([line, n]) => {\n let row: unknown\n try {\n row = JSON.parse(line)\n } catch {\n throw new Error(`${jsonl}:${n} is not valid JSON`)\n }\n if (!isObject(row)) throw new Error(`${jsonl}:${n} is not a JSON object`)\n return row\n })\n}\n"]}
|
|
1
|
+
{"version":3,"file":"definitions.js","sourceRoot":"","sources":["../../src/host/definitions.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAEH,OAAO,EAAE,UAAU,EAAE,WAAW,EAAE,YAAY,EAAE,MAAM,SAAS,CAAA;AAC/D,OAAO,EAAE,IAAI,EAAE,MAAM,WAAW,CAAA;AA8BhC,SAAS,QAAQ,CAAC,IAAY;IAC5B,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC;QAAE,OAAO,SAAS,CAAA;IACvC,MAAM,IAAI,GAAG,YAAY,CAAC,IAAI,EAAE,MAAM,CAAC,CAAA;IACvC,IA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O,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAA;IACnC,CAAC;IACD,MAAM,KAAK,GAAG,IAAI,CAAC,GAAG,EAAE,GAAG,MAAM,QAAQ,CAAC,CAAA;IAC1C,IAAI,CAAC,UAAU,CAAC,KAAK,CAAC;QAAE,OAAO,EAAE,CAAA;IACjC,OAAO,YAAY,CAAC,KAAK,EAAE,MAAM,CAAC;SAC/B,KAAK,CAAC,OAAO,CAAC;SACd,GAAG,CAAC,CAAC,IAAI,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,EAAE,EAAE,CAAC,GAAG,CAAC,CAAU,CAAC;SAC/C,MAAM,CAAC,CAAC,CAAC,IAAI,CAAC,EAAE,EAAE,CAAC,IAAI,KAAK,EAAE,CAAC;SAC/B,GAAG,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,EAAE,EAAE;QACjB,IAAI,GAAY,CAAA;QAChB,IAAI,CAAC;YACH,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,CAAA;QACxB,CAAC;QAAC,MAAM,CAAC;YACP,MAAM,IAAI,KAAK,CAAC,GAAG,KAAK,IAAI,CAAC,oBAAoB,CAAC,CAAA;QACpD,CAAC;QACD,IAAI,CAAC,QAAQ,CAAC,GAAG,CAAC;YAAE,MAAM,IAAI,KAAK,CAAC,GAAG,KAAK,IAAI,CAAC,uBAAuB,CAAC,CAAA;QACzE,OAAO,GAAG,CAAA;IACZ,CAAC,CAAC,CAAA;AACN,CAAC","sourcesContent":["/**\n * What the local host reads from the pwpack folder.\n *\n * app/definitions/auth.json who may enter (definitions.md, `auth.json`)\n * app/definitions/entities.json the collections the host keeps\n * app/surfaces/<key>.receipt.json the pages it serves\n * app/content/<typeId>.json the app's shipped records (data-protocol §6)\n * app/data/<typeId>.jsonl | .json development records, never published\n *\n * Read on every call, never cached: `pwf dev` edits these files while the\n * host runs, and a definition change must apply without a restart. An absent\n * file is \"not declared\"; an unreadable one is reported as an error rather\n * than guessed around.\n */\n\nimport { existsSync, readdirSync, readFileSync } from 'node:fs'\nimport { join } from 'node:path'\n\nexport interface AuthDeclaration {\n readonly required: boolean\n readonly topology: 'app' | 'external'\n readonly methods: readonly string[]\n readonly issuer?: {\n readonly issuer: string\n readonly clientId: string\n readonly scopes: readonly string[]\n readonly audience?: string\n }\n readonly access: {\n readonly roles: readonly string[]\n readonly rules: readonly { readonly subject: string; readonly model: string; readonly rule: string }[]\n }\n}\n\nexport interface EntityField {\n readonly name: string\n readonly type: string\n readonly required: boolean\n}\n\nexport interface EntityDeclaration {\n readonly typeId: string\n readonly displayName?: string\n readonly fields: readonly EntityField[]\n}\n\nfunction readJson(path: string): unknown {\n if (!existsSync(path)) return undefined\n const text = readFileSync(path, 'utf8')\n try {\n return JSON.parse(text) as unknown\n } catch (err) {\n throw new Error(`${path} is not valid JSON: ${(err as Error).message}`)\n }\n}\n\nconst isObject = (v: unknown): v is Record<string, unknown> => Boolean(v) && typeof v === 'object' && !Array.isArray(v)\nconst strings = (v: unknown): string[] => (Array.isArray(v) ? v.filter((x): x is string => typeof x === 'string') : [])\n\n/** `undefined` when the app declares no `auth.json` (or an empty one). */\nexport function readAuth(root: string): AuthDeclaration | undefined {\n const raw = readJson(join(root, 'app', 'definitions', 'auth.json'))\n if (!isObject(raw) || Object.keys(raw).length === 0) return undefined\n const topology = raw.topology === 'external' ? 'external' : 'app'\n const iss = isObject(raw.issuer) ? raw.issuer : undefined\n const access = isObject(raw.access) ? raw.access : {}\n const rules = (Array.isArray(access.rules) ? access.rules : [])\n .filter(isObject)\n .map((r) => ({ subject: String(r.subject ?? ''), model: String(r.model ?? ''), rule: String(r.rule ?? '') }))\n return {\n required: raw.required === true,\n topology,\n methods: strings(raw.methods),\n ...(iss && typeof iss.issuer === 'string' && typeof iss.clientId === 'string'\n ? {\n issuer: {\n issuer: iss.issuer,\n clientId: iss.clientId,\n scopes: Array.isArray(iss.scopes) ? strings(iss.scopes) : ['openid', 'profile', 'email'],\n ...(typeof iss.audience === 'string' && iss.audience ? { audience: iss.audience } : {}),\n },\n }\n : {}),\n access: { roles: strings(access.roles), rules },\n }\n}\n\nexport function readEntities(root: string): EntityDeclaration[] {\n const raw = readJson(join(root, 'app', 'definitions', 'entities.json'))\n const list = isObject(raw) && Array.isArray(raw.entities) ? raw.entities : []\n return list.filter(isObject).flatMap((e) => {\n if (typeof e.typeId !== 'string' || !e.typeId) return []\n const fields = (Array.isArray(e.fields) ? e.fields : []).filter(isObject).flatMap((f) =>\n typeof f.name === 'string' && f.name\n ? [{ name: f.name, type: typeof f.type === 'string' ? f.type : 'text', required: f.required === true }]\n : []\n )\n return [\n {\n typeId: e.typeId,\n ...(typeof e.displayName === 'string' ? { displayName: e.displayName } : {}),\n fields,\n },\n ]\n })\n}\n\n/** A page key is a file name, never a path. */\nexport const PAGE_KEY = /^[A-Za-z0-9][A-Za-z0-9_-]*$/\n\nexport function surfaceKeys(root: string): string[] {\n const dir = join(root, 'app', 'surfaces')\n if (!existsSync(dir)) return []\n return readdirSync(dir)\n .filter((f) => f.endsWith('.receipt.json'))\n .map((f) => f.slice(0, -'.receipt.json'.length))\n .filter((k) => PAGE_KEY.test(k))\n .sort()\n}\n\nexport function readReceipt(root: string, key: string): Record<string, unknown> | undefined {\n if (!PAGE_KEY.test(key)) return undefined\n const raw = readJson(join(root, 'app', 'surfaces', `${key}.receipt.json`))\n return isObject(raw) ? raw : undefined\n}\n\n/**\n * Seed rows for one collection: the app's content, then its development data.\n *\n * Two folders, one shape (data-protocol §6):\n * - `app/content/<typeId>.json` — records the app ships for every visitor; a\n * publisher inserts each one the record store does not hold yet.\n * - `app/data/<typeId>.json` — development and test records; never published.\n * A data row with the id of a content row replaces it here, so a developer can\n * try a variant without editing the content.\n */\nexport function readSeed(root: string, typeId: string): Record<string, unknown>[] {\n if (!PAGE_KEY.test(typeId)) return []\n const rows = new Map<string, Record<string, unknown>>()\n let anonymous = 0\n for (const row of [...readRecordsFile(join(root, 'app', 'content'), typeId), ...readRecordsFile(join(root, 'app', 'data'), typeId)]) {\n const id = typeof row.id === 'string' || typeof row.id === 'number' ? String(row.id) : `\\0${anonymous++}`\n rows.set(id, row)\n }\n return [...rows.values()]\n}\n\n/**\n * `<dir>/<typeId>.json` holding `{ \"data\": [ …records ] }` — the same `data`\n * envelope a record list answer uses. A record may carry its own `id`;\n * `createdAt`/`updatedAt` are filled when absent. Also accepted, for\n * hand-written files only: `<dir>/<typeId>.jsonl`, one JSON object per line\n * (blank lines skipped), read when no `.json` file exists.\n */\nfunction readRecordsFile(dir: string, typeId: string): Record<string, unknown>[] {\n const jsonPath = join(dir, `${typeId}.json`)\n const json = readJson(jsonPath)\n if (json !== undefined) {\n if (!isObject(json) || !Array.isArray(json.data)) {\n throw new Error(`${jsonPath} must be { \"data\": [ ...records ] }`)\n }\n return json.data.filter(isObject)\n }\n const jsonl = join(dir, `${typeId}.jsonl`)\n if (!existsSync(jsonl)) return []\n return readFileSync(jsonl, 'utf8')\n .split(/\\r?\\n/)\n .map((line, i) => [line.trim(), i + 1] as const)\n .filter(([line]) => line !== '')\n .map(([line, n]) => {\n let row: unknown\n try {\n row = JSON.parse(line)\n } catch {\n throw new Error(`${jsonl}:${n} is not valid JSON`)\n }\n if (!isObject(row)) throw new Error(`${jsonl}:${n} is not a JSON object`)\n return row\n })\n}\n"]}
|
|
@@ -2,8 +2,9 @@
|
|
|
2
2
|
* The local host — the session protocol and the data protocol, in process,
|
|
3
3
|
* for development.
|
|
4
4
|
*
|
|
5
|
-
* NOT A PRODUCTION SERVER. Records live in memory and vanish on restart;
|
|
6
|
-
*
|
|
5
|
+
* NOT A PRODUCTION SERVER. Records live in memory and vanish on restart; no
|
|
6
|
+
* password is checked (the development e-mail is the development user, any
|
|
7
|
+
* other e-mail a plain member); the issuer stand-in mints
|
|
7
8
|
* unsigned ID tokens; there is no rate limit, no CORS, no TLS. It exists so an
|
|
8
9
|
* app that declares data and sign-in runs on a laptop with no hosted service,
|
|
9
10
|
* and so the runner's sign-in wall, account control, gate and data paths are
|
package/dist/host/local-host.js
CHANGED
|
@@ -2,8 +2,9 @@
|
|
|
2
2
|
* The local host — the session protocol and the data protocol, in process,
|
|
3
3
|
* for development.
|
|
4
4
|
*
|
|
5
|
-
* NOT A PRODUCTION SERVER. Records live in memory and vanish on restart;
|
|
6
|
-
*
|
|
5
|
+
* NOT A PRODUCTION SERVER. Records live in memory and vanish on restart; no
|
|
6
|
+
* password is checked (the development e-mail is the development user, any
|
|
7
|
+
* other e-mail a plain member); the issuer stand-in mints
|
|
7
8
|
* unsigned ID tokens; there is no rate limit, no CORS, no TLS. It exists so an
|
|
8
9
|
* app that declares data and sign-in runs on a laptop with no hosted service,
|
|
9
10
|
* and so the runner's sign-in wall, account control, gate and data paths are
|
|
@@ -140,10 +141,17 @@ export const createLocalHost = (options) => {
|
|
|
140
141
|
const issuer = new DevIssuer(bearer, user);
|
|
141
142
|
const originOf = (req) => `http://${req.headers.host ?? 'localhost'}`;
|
|
142
143
|
const principalOf = (req) => bearer.get(credentialOf(req))?.principal;
|
|
143
|
-
function startSession() {
|
|
144
|
+
function startSession(principal = user) {
|
|
144
145
|
const expiresAt = Date.now() + SESSION_TTL_MS;
|
|
145
|
-
const token = bearer.issue({ principal
|
|
146
|
-
return { token, expiresAt: new Date(expiresAt).toISOString(), principal
|
|
146
|
+
const token = bearer.issue({ principal, kind: 'session', expiresAt });
|
|
147
|
+
return { token, expiresAt: new Date(expiresAt).toISOString(), principal };
|
|
148
|
+
}
|
|
149
|
+
/** The password door signs in whoever it is told: the development user, or a plain member for any other e-mail. */
|
|
150
|
+
function principalNamed(email) {
|
|
151
|
+
if (typeof email !== 'string' || !email.trim() || email.trim().toLowerCase() === user.email.toLowerCase())
|
|
152
|
+
return user;
|
|
153
|
+
const address = email.trim().toLowerCase();
|
|
154
|
+
return { id: `dev-${address}`, email: address, displayName: address };
|
|
147
155
|
}
|
|
148
156
|
const sessionCookie = (token, maxAgeS) => `${SESSION_COOKIE}=${encodeURIComponent(token)}; Path=${prefix}/_auth; HttpOnly; SameSite=Lax; Max-Age=${maxAgeS}`;
|
|
149
157
|
function requireRunnerRequest(req) {
|
|
@@ -176,13 +184,13 @@ export const createLocalHost = (options) => {
|
|
|
176
184
|
sendJson(res, 200, { data: { signedOut: true } });
|
|
177
185
|
return;
|
|
178
186
|
}
|
|
179
|
-
// login / register: the
|
|
180
|
-
//
|
|
181
|
-
await readJsonObject(req);
|
|
187
|
+
// login / register: the password is not checked. The e-mail picks who
|
|
188
|
+
// signs in (see principalNamed), so access rules can be tried as a member.
|
|
189
|
+
const credentials = await readJsonObject(req);
|
|
182
190
|
if (!auth || auth.topology !== 'app' || !auth.methods.includes('password')) {
|
|
183
191
|
throw new HostError(404, 'NO_PASSWORD_DOOR', 'This app declares no password sign-in.');
|
|
184
192
|
}
|
|
185
|
-
sendJson(res, action === 'register' ? 201 : 200, { data: startSession() });
|
|
193
|
+
sendJson(res, action === 'register' ? 201 : 200, { data: startSession(principalNamed(credentials.email)) });
|
|
186
194
|
}
|
|
187
195
|
function gateway(req, res, url, parts) {
|
|
188
196
|
const [action, method] = parts;
|
|
@@ -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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E,IAAY;IACnD,MAAM,CAAC,IAAI,EAAE,IAAI,CAAC,GAAG,SAAS,CAAC,QAAQ,CAAC,CAAA;IACxC,OAAO,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; 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;AAGx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,SAAS,CAAC,GAAG,EAAE,YAAY,EAAE,GAAG,YAAY,KAAK,CAAC,CAAC,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,CAAA;gBACpG,CAAC;YACH,CAAC;YACD,OAAO,IAAI,CAAA;QACb,CAAC;QAED,KAAK;YACH,OAAO,CAAC,KAAK,EAAE,CAAA;YACf,MAAM,CAAC,KAAK,EAAE,CAAA;YACd,YAAY,CAAC,KAAK,EAAE,CAAA;YACpB,MAAM,CAAC,KAAK,EAAE,CAAA;QAChB,CAAC;KACF,CAAA;AACH,CAAC,CAAA;AAED,SAAS,aAAa,CAAC,QAAgB,EAAE,IAAY;IACnD,MAAM,CAAC,IAAI,EAAE,IAAI,CAAC,GAAG,SAAS,CAAC,QAAQ,CAAC,CAAA;IACxC,OAAO,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 */\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(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"]}
|
package/dist/host/records.d.ts
CHANGED
|
@@ -2,30 +2,42 @@
|
|
|
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
|
|
6
|
-
* `{ …fields, id, entityType, createdAt, updatedAt }`, fields spread
|
|
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
|
|
10
|
-
* hosted session server decides:
|
|
9
|
+
* ACCESS is the app's `auth.json` `access.rules` (definitions, `access`):
|
|
11
10
|
*
|
|
12
|
-
* - `
|
|
13
|
-
*
|
|
14
|
-
* - A
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
*
|
|
18
|
-
*
|
|
19
|
-
*
|
|
20
|
-
*
|
|
21
|
-
*
|
|
22
|
-
* write it.
|
|
11
|
+
* - `required: true`: every data request needs a session (`401`).
|
|
12
|
+
* - A model no rule names is open to every visitor.
|
|
13
|
+
* - A model some rule names is closed: a request passes when a rule whose
|
|
14
|
+
* subject matches the caller (`public`, `member`, or one of the caller's
|
|
15
|
+
* roles) grants its verb. `own` limits the grant to the caller's records.
|
|
16
|
+
* - Refused: `401 SIGN_IN_REQUIRED` without a session, `403 FORBIDDEN` with
|
|
17
|
+
* one; a record outside an `own` grant is `404`.
|
|
18
|
+
*
|
|
19
|
+
* The development user carries every role `access.roles` declares, so the
|
|
20
|
+
* author can try the app as staff; any other e-mail signs in as a plain member.
|
|
23
21
|
*/
|
|
24
22
|
import { type AuthDeclaration, type EntityDeclaration } from './definitions.js';
|
|
25
23
|
import { type AggregateResult, type Row } from './query.js';
|
|
26
24
|
import type { Principal } from './tokens.js';
|
|
27
25
|
export type Scope = 'project' | 'owner';
|
|
28
|
-
|
|
26
|
+
type Verb = 'create' | 'list' | 'view' | 'update' | 'delete' | 'count';
|
|
27
|
+
/** What one verb allows the caller: nothing, their own records, or every record. */
|
|
28
|
+
type Reach = 'none' | 'own' | 'all';
|
|
29
|
+
export type Access = Readonly<Record<Verb, Reach>>;
|
|
30
|
+
/** The words of a rule: verbs and `own`; anything else is ignored. */
|
|
31
|
+
export declare function parseRule(rule: string): {
|
|
32
|
+
verbs: Verb[];
|
|
33
|
+
own: boolean;
|
|
34
|
+
unknown: string[];
|
|
35
|
+
};
|
|
36
|
+
/** What `caller` (with `roles`) may do with `entity` under the app's rules. */
|
|
37
|
+
export declare function accessOf(entity: EntityDeclaration, auth: AuthDeclaration | undefined, caller: {
|
|
38
|
+
readonly principal: Principal | undefined;
|
|
39
|
+
readonly roles: readonly string[];
|
|
40
|
+
}): Access;
|
|
29
41
|
export interface Caller {
|
|
30
42
|
readonly principal: Principal | undefined;
|
|
31
43
|
}
|
|
@@ -58,12 +70,14 @@ export declare class RecordStore {
|
|
|
58
70
|
constructor(root: string, devUser: Principal);
|
|
59
71
|
reset(): void;
|
|
60
72
|
private collection;
|
|
61
|
-
/**
|
|
62
|
-
private
|
|
63
|
-
/** The
|
|
64
|
-
private
|
|
73
|
+
/** What the caller may do here; refuses a caller the app does not let in at all. */
|
|
74
|
+
private access;
|
|
75
|
+
/** The reach of `verb`, refusing when it is none. */
|
|
76
|
+
private allow;
|
|
77
|
+
/** The rows within `reach`, newest change first, after `filter`. */
|
|
78
|
+
private rows;
|
|
65
79
|
list(target: Target, params: URLSearchParams): ListAnswer;
|
|
66
|
-
/** `/count` (`plainCount`) or `/aggregate?fn&field
|
|
80
|
+
/** `/count` (`plainCount`) or `/aggregate?fn&field`: over every row with `count`, else over the rows `list` reaches. */
|
|
67
81
|
aggregate(target: Target, params: URLSearchParams, plainCount: boolean): AggregateAnswer;
|
|
68
82
|
private find;
|
|
69
83
|
read(target: Target, id: string): Row;
|
|
@@ -71,3 +85,4 @@ export declare class RecordStore {
|
|
|
71
85
|
update(target: Target, id: string, body: Record<string, unknown>): Row;
|
|
72
86
|
remove(target: Target, id: string): void;
|
|
73
87
|
}
|
|
88
|
+
export {};
|