@aarwitz/tapp 0.21.2 → 0.23.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.
@@ -0,0 +1,131 @@
1
+ // A tapp account is an email address, nothing more. It exists so the hosted Studio can do what
2
+ // the local one does — stop at a sign-in and ask, and remember the answer — for a person it can
3
+ // tell apart from the next visitor. There are no passwords here: a sign-in is a link mailed to
4
+ // the address, used once, and a session cookie after that.
5
+ //
6
+ // Nothing secret is stored in the clear. A link token and a session token are random; only their
7
+ // SHA-256 lands on disk, so a copy of this directory cannot sign anyone in. Each account gets its
8
+ // own encrypted actor store (see actor-store.js) under its directory, so one person's test
9
+ // accounts are never listed under another's.
10
+ //
11
+ // Layout: TAPP_HOME/accounts/
12
+ // by-email/<sha256(email)> → account id
13
+ // accounts/<id>.json { id, email, createdAt, lastSeenAt }
14
+ // links/<sha256(token)>.json { email, expiresAt } (removed on use)
15
+ // sessions/<sha256(token)>.json { accountId, createdAt, expiresAt }
16
+ // actors/<id>/ that account's ActorStore root
17
+ import crypto from "node:crypto";
18
+ import fs from "node:fs";
19
+ import os from "node:os";
20
+ import path from "node:path";
21
+
22
+ export const LINK_TTL_MS = 15 * 60 * 1000;
23
+ export const SESSION_TTL_MS = 90 * 24 * 60 * 60 * 1000;
24
+ // One address may ask for this many links in a ten-minute window; more is someone else's mailbox
25
+ // being flooded through us.
26
+ const LINKS_PER_WINDOW = 5;
27
+ const LINK_WINDOW_MS = 10 * 60 * 1000;
28
+
29
+ export function accountStoreRoot(env = process.env) {
30
+ const home = (env.TAPP_HOME || "").trim() || path.join(os.homedir(), ".tapp");
31
+ return path.join(home, "accounts");
32
+ }
33
+
34
+ const EMAIL = /^[^\s@]{1,64}@[^\s@]{1,255}\.[^\s@]{2,}$/;
35
+ export function normalizeEmail(value) {
36
+ const email = String(value || "").trim().toLowerCase();
37
+ if (!EMAIL.test(email)) throw Object.assign(new Error("That does not look like an email address"), { statusCode: 400 });
38
+ return email;
39
+ }
40
+
41
+ const sha = (value) => crypto.createHash("sha256").update(String(value)).digest("hex");
42
+ const token = () => crypto.randomBytes(32).toString("base64url");
43
+
44
+ function readJson(file) {
45
+ try { return JSON.parse(fs.readFileSync(file, "utf8")); } catch { return null; }
46
+ }
47
+
48
+ function writeJson(file, value) {
49
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
50
+ const tmp = `${file}.${process.pid}.tmp`;
51
+ fs.writeFileSync(tmp, JSON.stringify(value), { mode: 0o600 });
52
+ fs.renameSync(tmp, file);
53
+ }
54
+
55
+ export class AccountStore {
56
+ constructor({ root = accountStoreRoot(), now = () => Date.now() } = {}) {
57
+ this.root = root;
58
+ this.now = now;
59
+ this.linkRequests = new Map();
60
+ }
61
+
62
+ #file(kind, key) { return path.join(this.root, kind, `${key}.json`); }
63
+
64
+ /** Ask for a sign-in link. Returns the token to mail — the only time it exists in the clear. */
65
+ requestLink(rawEmail) {
66
+ const email = normalizeEmail(rawEmail);
67
+ const now = this.now();
68
+ const recent = (this.linkRequests.get(email) || []).filter((at) => now - at < LINK_WINDOW_MS);
69
+ if (recent.length >= LINKS_PER_WINDOW) {
70
+ throw Object.assign(new Error("A few links were already sent to that address. Check your inbox, then try again in a little while."), { statusCode: 429 });
71
+ }
72
+ recent.push(now);
73
+ this.linkRequests.set(email, recent);
74
+ const value = token();
75
+ writeJson(this.#file("links", sha(value)), { email, expiresAt: new Date(now + LINK_TTL_MS).toISOString() });
76
+ return { email, token: value };
77
+ }
78
+
79
+ /** Use a link once. Returns a session token and the account, or null for a bad or spent link. */
80
+ redeem(value) {
81
+ if (!/^[A-Za-z0-9_-]{20,}$/.test(String(value || ""))) return null;
82
+ const file = this.#file("links", sha(value));
83
+ const link = readJson(file);
84
+ try { fs.rmSync(file, { force: true }); } catch { /* spent either way */ }
85
+ if (!link || Date.parse(link.expiresAt) < this.now()) return null;
86
+ const account = this.#ensureAccount(link.email);
87
+ const session = token();
88
+ writeJson(this.#file("sessions", sha(session)), { accountId: account.id, createdAt: new Date(this.now()).toISOString(), expiresAt: new Date(this.now() + SESSION_TTL_MS).toISOString() });
89
+ return { session, account };
90
+ }
91
+
92
+ /** The account behind a session cookie, or null. */
93
+ sessionAccount(value) {
94
+ if (!/^[A-Za-z0-9_-]{20,}$/.test(String(value || ""))) return null;
95
+ const session = readJson(this.#file("sessions", sha(value)));
96
+ if (!session || Date.parse(session.expiresAt) < this.now()) return null;
97
+ const account = readJson(this.#file("accounts", session.accountId));
98
+ if (!account) return null;
99
+ // lastSeenAt is coarse on purpose: a day, not a request log.
100
+ const day = new Date(this.now()).toISOString().slice(0, 10);
101
+ if ((account.lastSeenAt || "").slice(0, 10) !== day) { account.lastSeenAt = new Date(this.now()).toISOString(); writeJson(this.#file("accounts", account.id), account); }
102
+ return account;
103
+ }
104
+
105
+ signOut(value) {
106
+ if (!/^[A-Za-z0-9_-]{20,}$/.test(String(value || ""))) return;
107
+ try { fs.rmSync(this.#file("sessions", sha(value)), { force: true }); } catch { /* already gone */ }
108
+ }
109
+
110
+ /** Where this account's encrypted test accounts live. */
111
+ actorRoot(accountId) {
112
+ if (!/^[a-f0-9]{24}$/.test(String(accountId || ""))) throw new Error("Not an account id");
113
+ return path.join(this.root, "actors", accountId);
114
+ }
115
+
116
+ #ensureAccount(email) {
117
+ const indexFile = path.join(this.root, "by-email", sha(email));
118
+ let id = null;
119
+ try { id = fs.readFileSync(indexFile, "utf8").trim(); } catch { /* new */ }
120
+ if (id) {
121
+ const existing = readJson(this.#file("accounts", id));
122
+ if (existing) return existing;
123
+ }
124
+ id = crypto.randomBytes(12).toString("hex");
125
+ const account = { id, email, createdAt: new Date(this.now()).toISOString(), lastSeenAt: new Date(this.now()).toISOString() };
126
+ writeJson(this.#file("accounts", id), account);
127
+ fs.mkdirSync(path.dirname(indexFile), { recursive: true, mode: 0o700 });
128
+ fs.writeFileSync(indexFile, `${id}\n`, { mode: 0o600 });
129
+ return account;
130
+ }
131
+ }
@@ -0,0 +1,149 @@
1
+ // Where tapp keeps what it has been told about an application's test accounts, and the signed-in
2
+ // sessions it has built with them.
3
+ //
4
+ // The point of the store is that a login happens once. The first time tapp meets a sign-in it
5
+ // asks (see the OCQA_AWAIT_INPUT protocol in web-explorer.js); after a successful sign-in the
6
+ // browser's storageState — cookies and local storage, which is what "being signed in" is — is kept
7
+ // here, so the next run starts inside the application. A login that needs a code from a phone or
8
+ // an email link therefore only ever has to be done by a person once.
9
+ //
10
+ // Everything here is encrypted at rest. The key is generated once into TAPP_HOME/actors/.key
11
+ // (0600). Each record is AES-256-GCM with the host and actor name as additional authenticated
12
+ // data, so a record copied between applications or actors does not decrypt — the same shape the
13
+ // hosted product's service-access store uses. Nothing in this module ever logs a value.
14
+ //
15
+ // Layout: TAPP_HOME/actors/<host>/<actor>.json
16
+ import crypto from "node:crypto";
17
+ import fs from "node:fs";
18
+ import os from "node:os";
19
+ import path from "node:path";
20
+
21
+ const KEY_FILE = ".key";
22
+ const CIPHER = "aes-256-gcm";
23
+ const INFO = "tapp-actor-store-v1";
24
+
25
+ export function actorStoreRoot(env = process.env) {
26
+ const home = (env.TAPP_HOME || "").trim() || path.join(os.homedir(), ".tapp");
27
+ return path.join(home, "actors");
28
+ }
29
+
30
+ // A host is the application; everything about it keys off the origin's host, never the full URL.
31
+ export function hostKey(target) {
32
+ try { return new URL(String(target)).host.toLowerCase(); } catch { return String(target || "").trim().toLowerCase(); }
33
+ }
34
+
35
+ const ACTOR = /^[A-Za-z][A-Za-z0-9_-]{0,63}$/;
36
+ export function normalizeActorName(name) {
37
+ const value = String(name || "default").trim();
38
+ if (!ACTOR.test(value)) throw new Error(`Actor name '${value}' must be letters, digits, _ or - (max 64)`);
39
+ return value;
40
+ }
41
+
42
+ function loadKey(root) {
43
+ const keyPath = path.join(root, KEY_FILE);
44
+ try {
45
+ const raw = fs.readFileSync(keyPath);
46
+ if (raw.length === 32) return raw;
47
+ } catch { /* first use */ }
48
+ fs.mkdirSync(root, { recursive: true, mode: 0o700 });
49
+ const key = crypto.randomBytes(32);
50
+ fs.writeFileSync(keyPath, key, { mode: 0o600 });
51
+ return key;
52
+ }
53
+
54
+ function derive(root, host, actor) {
55
+ return Buffer.from(crypto.hkdfSync("sha256", loadKey(root), `${host}/${actor}`, INFO, 32));
56
+ }
57
+
58
+ function seal(key, aad, value) {
59
+ const iv = crypto.randomBytes(12);
60
+ const cipher = crypto.createCipheriv(CIPHER, key, iv);
61
+ cipher.setAAD(Buffer.from(aad));
62
+ const ciphertext = Buffer.concat([cipher.update(JSON.stringify(value), "utf8"), cipher.final()]);
63
+ return { v: 1, iv: iv.toString("base64"), tag: cipher.getAuthTag().toString("base64"), data: ciphertext.toString("base64") };
64
+ }
65
+
66
+ function unseal(key, aad, sealed) {
67
+ const decipher = crypto.createDecipheriv(CIPHER, key, Buffer.from(sealed.iv, "base64"));
68
+ decipher.setAAD(Buffer.from(aad));
69
+ decipher.setAuthTag(Buffer.from(sealed.tag, "base64"));
70
+ return JSON.parse(Buffer.concat([decipher.update(Buffer.from(sealed.data, "base64")), decipher.final()]).toString("utf8"));
71
+ }
72
+
73
+ function recordPath(root, host, actor) {
74
+ return path.join(root, host.replace(/[^a-z0-9.:-]/gi, "_"), `${actor}.json`);
75
+ }
76
+
77
+ /**
78
+ * The store for one application. `credentials` are what a person typed; `session` is the
79
+ * browser's storageState after a sign-in worked. Either may be absent.
80
+ */
81
+ export class ActorStore {
82
+ constructor({ root = actorStoreRoot() } = {}) {
83
+ this.root = root;
84
+ }
85
+
86
+ read(target, actorName = "default") {
87
+ const host = hostKey(target);
88
+ const actor = normalizeActorName(actorName);
89
+ const file = recordPath(this.root, host, actor);
90
+ let sealed;
91
+ try { sealed = JSON.parse(fs.readFileSync(file, "utf8")); } catch { return null; }
92
+ try {
93
+ const record = unseal(derive(this.root, host, actor), `${host}/${actor}`, sealed);
94
+ return { host, actor, ...record };
95
+ } catch {
96
+ // A record that does not authenticate is treated as absent, never as partially trusted.
97
+ return null;
98
+ }
99
+ }
100
+
101
+ write(target, actorName, record) {
102
+ const host = hostKey(target);
103
+ const actor = normalizeActorName(actorName);
104
+ const prior = this.read(target, actor) || {};
105
+ const next = {
106
+ credentials: record.credentials ?? prior.credentials ?? null,
107
+ session: record.session ?? prior.session ?? null,
108
+ updatedAt: new Date().toISOString(),
109
+ sessionSavedAt: record.session ? new Date().toISOString() : (prior.sessionSavedAt ?? null),
110
+ };
111
+ const file = recordPath(this.root, host, actor);
112
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 });
113
+ const sealed = seal(derive(this.root, host, actor), `${host}/${actor}`, next);
114
+ const tmp = `${file}.${process.pid}.tmp`;
115
+ fs.writeFileSync(tmp, JSON.stringify(sealed), { mode: 0o600 });
116
+ fs.renameSync(tmp, file);
117
+ return { host, actor, sessionSavedAt: next.sessionSavedAt };
118
+ }
119
+
120
+ forget(target, actorName = "default") {
121
+ const host = hostKey(target);
122
+ const actor = normalizeActorName(actorName);
123
+ try { fs.rmSync(recordPath(this.root, host, actor), { force: true }); return true; } catch { return false; }
124
+ }
125
+
126
+ // Names only — this is what a UI may show. Never the records.
127
+ list(target) {
128
+ const host = hostKey(target);
129
+ const dir = path.dirname(recordPath(this.root, host, "x"));
130
+ let names = [];
131
+ try { names = fs.readdirSync(dir).filter((n) => n.endsWith(".json")).map((n) => n.slice(0, -5)); } catch { return []; }
132
+ return names.map((actor) => {
133
+ const record = this.read(target, actor);
134
+ return { actor, hasCredentials: !!record?.credentials, hasSession: !!record?.session, sessionSavedAt: record?.sessionSavedAt || null };
135
+ });
136
+ }
137
+
138
+ // Playwright wants storageState as a file path or an object; a path keeps the object out of
139
+ // argument lists and logs. The file is 0600 and removed by the caller after the context opens.
140
+ sessionFile(target, actorName = "default") {
141
+ const record = this.read(target, actorName);
142
+ if (!record?.session) return null;
143
+ const dir = path.join(os.tmpdir(), "tapp-sessions");
144
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
145
+ const file = path.join(dir, `${crypto.randomBytes(8).toString("hex")}.json`);
146
+ fs.writeFileSync(file, JSON.stringify(record.session), { mode: 0o600 });
147
+ return file;
148
+ }
149
+ }