@runeditrun/rer 0.2.32 → 0.2.33

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,5 +1,17 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.33
4
+
5
+ - **CodeQL-clean mail and logout copies.** mail's `parseAddress`, `parseHeaders` and `messageIds` now parse in linear time, without backtracking regular expressions. Results and error codes are unchanged, and U+2028/U+2029 in a display name or header line is still refused. In dependencies' back-channel logout, the session fence is read from the exact `events` key with `Object.hasOwn`. Seeds that patched these files in their recorded Base copies can now refresh to Base's bytes.
6
+ - **Signing out of a hosted demo ends the copy.** In a native hosted demo, `POST /auth/signout` first lets the seed sign the visitor out. The visitor's copy then ends and its storage is erased, the same as when the hour or idle time runs out. A form navigation gets the ended page with "Start a new demo"; a script gets the seed's own answer, and its next page load finds the ended page. A refused sign-out (4xx/5xx) leaves the copy running.
7
+ - **An unreadable demo start is a 400.** A `POST /__demo/start` whose body is not a readable form (an empty body, JSON, or broken multipart) is refused with 400 "The start request was not a readable form." before the human check or any reservation, instead of being reported as a failed start.
8
+
9
+ ### Upgrade notes
10
+
11
+ - Update the exact rer package pin, or refresh vendored operating commands, to receive these changes.
12
+ - A seed that fixed `modules/dependencies/logout.mjs` or mail files in its own copy runs `refresh-base` to the release commit. If it dropped those files from its copy record, it puts Base's bytes back with `git -C <base> show <commit>:<path>`, re-records the containing copy (`record-base src/modules/dependencies modules/dependencies <commit>`, and the same for `modules/mail`), and expects `verify-base` drift 0.
13
+ - A hosted demo picks up the sign-out and start changes on its next `rer deploy --demo`.
14
+
3
15
  ## 0.2.32
4
16
 
5
17
  - **One line from nothing to a running seed.** `rer dev <repo>` clones the seed, installs its dependencies, sets up the local owner and starts the signed-in app, so `npx -y @runeditrun/rer dev just-every/run-inkwell` works from an empty folder and also installs the rer CLI. `rer setup <repo>` stops after setup and prints the next command; `rer install <repo>` stops after dependencies. `<repo>` is `<owner>/<repo>`, a GitHub HTTPS URL (with or without `.git`) or any git URL. The clone goes into `./<repo name>` unless `--dir DIR` says otherwise; an existing clone of the same repository is reused and any other non-empty folder is refused. Inside a checkout with no repo argument every verb behaves as before. `install.sh` forwards its arguments after installing (`curl -fsSL https://runeditrun.com/install.sh | sh -s -- dev just-every/run-inkwell`). Verb help and `rer describe` list the repository forms, also for checkouts that pin an older rer.
@@ -99,6 +99,19 @@ export class NativeDemo extends DurableObject {
99
99
  if (!runtime) return endedPage(this.env, { headers: { 'set-cookie': clearCookie(this.env) } });
100
100
  return application(this.env, this.ctx, this.ctx.id.toString(), runtime).fetch(request);
101
101
  }
102
+ // The seed signs the visitor out, then the copy ends as an expired one does.
103
+ // A form navigation gets the ended page; a script gets the seed's answer and
104
+ // its next page load finds the ended page.
105
+ async signOut(request) {
106
+ const runtime = await this.session();
107
+ if (!runtime) return endedPage(this.env, { headers: { 'set-cookie': clearCookie(this.env) } });
108
+ const response = await application(this.env, this.ctx, this.ctx.id.toString(), runtime).fetch(request);
109
+ if (response.status >= 400) return response;
110
+ const body = await response.arrayBuffer();
111
+ await this.end();
112
+ if (/text\/html/.test(request.headers.get('accept') ?? '')) return endedPage(this.env, { headers: { 'set-cookie': clearCookie(this.env) } });
113
+ return new Response(response.status === 204 ? null : body, response);
114
+ }
102
115
  database(binding, method, args) { return database(this, binding, method, args); }
103
116
  object(binding, id, method, args) { return object(this, binding, id, method, args); }
104
117
  r2(binding, method, args) { return r2(this, binding, method, args); }
@@ -44,11 +44,11 @@ export function startPage(env, { status = 200, notice, pending = false, headers
44
44
  <p class="note" id="note">${pending ? 'Your demo will open automatically when ready.' : 'Complete the human check to start your demo.'}</p><noscript><p class="note">The human check needs JavaScript. Turn it on to start the demo.</p></noscript><p class="visually-hidden" id="status" role="status"></p></form>` });
45
45
  }
46
46
 
47
- /** A demo whose hour or idle time is up: its isolate and data are gone. */
47
+ /** A demo signed out of, or whose hour or idle time is up: its isolate and data are gone. */
48
48
  export function endedPage(env, { status = 410, headers = {} } = {}) {
49
49
  const name = escape(env.DEMO_NAME);
50
50
  return html(env, { page: 'ended', title: 'This demo has ended', status, headers, body: `<h1 id="title">This demo has ended</h1>
51
- <p class="intro">Demos last an hour, or until 15 minutes pass with nothing happening. Its copy of ${name} and everything in it have been deleted.</p>
51
+ <p class="intro">A demo ends when you sign out, after an hour, or after 15 minutes with nothing happening. Its copy of ${name} and everything in it have been deleted.</p>
52
52
  <a class="button" href="${escape(env.DEMO_ORIGIN)}/">Start a new demo</a><p class="secondary"><a href="${escape(new URL(env.DEMO_SITE).origin)}/run">Run ${name} yourself</a></p>` });
53
53
  }
54
54
 
@@ -86,7 +86,9 @@ async function start(request, env, ctx) {
86
86
  try {
87
87
  const ip = request.headers.get('cf-connecting-ip') ?? '';
88
88
  if (!(await bounded(env.STARTS.limit({ key: ip }), 1000)).success) return refuse(429, 'Too many demos started from your network. Try again in a minute.');
89
- const form = await bounded(request.formData(), 1000);
89
+ // A probe or bot without a readable form is a bad request, not a failed start.
90
+ const form = await bounded(request.formData(), 1000).catch(() => null);
91
+ if (!form) return refuse(400, 'The start request was not a readable form. Reload the page and try again.');
90
92
  if (!await bounded(human(env, form.get('cf-turnstile-response'), ip), 5000)) return refuse(403, 'The check did not pass. Try again.');
91
93
  // A retry while the original start is pending resumes that copy, not a
92
94
  // second reservation that the visitor can never use.
@@ -159,6 +161,9 @@ export default {
159
161
  const state = await bounded(env.DEMO.get(id).status(), 2000).catch(() => null);
160
162
  if (state?.phase === 'starting') return progress(request, env, id, state);
161
163
  }
164
+ // A demo's owner has no mailbox, so the seed's sign-in page would strand
165
+ // the visitor: signing out ends their copy and shows the ended page.
166
+ if (url.pathname === '/auth/signout' && request.method === 'POST') return env.DEMO.get(id).signOut(request);
162
167
  return env.DEMO.get(id).fetch(request);
163
168
  }
164
169
  if (!['GET', 'HEAD'].includes(request.method)) return new Response('Start a demo first.', { status: 403 });
@@ -23,8 +23,9 @@ export async function backchannelLogout({db,config,request,clock=Date.now,fetch:
23
23
  const events=Object.keys(c.events);insist(events.length>0 && events.every(k=>[LOGOUT_EVENT,FENCE_EVENT].includes(k) && c.events[k] && typeof c.events[k]==='object' && !Array.isArray(c.events[k]) && Object.keys(c.events[k]).length===0));
24
24
  for(const key of ['sub','sid']) if(Object.hasOwn(c,key)) insist(typeof c[key]==='string' && c[key].length>0 && c[key].length<=255);
25
25
  insist(c.sub || c.sid);
26
+ const fence=Object.hasOwn(c.events,FENCE_EVENT);
26
27
  if(native) {
27
- const consumed=await native.consumeLogout({claims:c,link,now:clock(),fence:events.includes(FENCE_EVENT)});
28
+ const consumed=await native.consumeLogout({claims:c,link,now:clock(),fence});
28
29
  insist(consumed,'logout_already_used',409);
29
30
  return new Response(null,{status:204});
30
31
  }
@@ -33,7 +34,7 @@ export async function backchannelLogout({db,config,request,clock=Date.now,fetch:
33
34
  const subject=c.sub??(rows.length===1?rows[0].subject:null);insist(subject);
34
35
  const person=await db.prepare('SELECT operator_id FROM oa_external_identities WHERE issuer=? AND subject=?').bind(c.iss,subject).first();insist(person);
35
36
  const statements=[db.prepare(`INSERT INTO oa_logout_events(issuer,jti,consumed_at) VALUES(?,?,CASE WHEN EXISTS(SELECT 1 FROM rer_dependency_link WHERE interface='oidc-provider@1' AND issuer=? AND client_id=? AND metadata=? AND needs_relink=0 AND linked_at=?) AND EXISTS(SELECT 1 FROM oa_external_identities WHERE issuer=? AND subject=? AND operator_id=?) THEN ? ELSE -1 END)`).bind(c.iss,c.jti,link.issuer,link.client_id,JSON.stringify(link.metadata),link.linked_at,c.iss,subject,person.operator_id,clock())];
36
- if(events.includes(FENCE_EVENT)) statements.push(db.prepare('UPDATE oa_operators SET version=version+1 WHERE id=?').bind(person.operator_id));
37
+ if(fence) statements.push(db.prepare('UPDATE oa_operators SET version=version+1 WHERE id=?').bind(person.operator_id));
37
38
  statements.push(db.prepare(`UPDATE oa_sessions SET revoked_at=COALESCE(revoked_at,?) WHERE id IN
38
39
  (SELECT session_id FROM oa_provider_sessions WHERE issuer=? AND subject=? AND (? IS NULL OR sid=?))`).bind(clock(),c.iss,subject,c.sid??null,c.sid??null));
39
40
  try { await db.batch(statements); } catch { insist(false,'logout_already_used',409); }
@@ -50,14 +50,23 @@ export function validateConfig(config, dependencies = {}) {
50
50
 
51
51
  export function parseAddress(value) {
52
52
  bounded(value, 998, 'invalid_address');
53
- const match = value.trim().match(/^(?:(.*?)\s*<([^<>]+)>|([^<>]+))$/u);
54
- const email = (match?.[2] ?? match?.[3] ?? '').trim();
53
+ const text = value.trim();
54
+ let email = '', name;
55
+ if (text.endsWith('>')) {
56
+ // Display name, then the last '<' opens the angle address.
57
+ const open = text.lastIndexOf('<');
58
+ const inner = text.slice(open + 1, -1);
59
+ const display = text.slice(0, Math.max(open, 0)).trimEnd();
60
+ if (open >= 0 && inner && !inner.includes('>') && !/[\u2028\u2029]/.test(display)) {
61
+ email = inner.trim(); name = display;
62
+ }
63
+ } else if (text && !text.includes('<') && !text.includes('>')) email = text;
55
64
  // Conservative mailbox subset; never serialize multiple mailboxes as one.
56
65
  const parts = email.split('@');
57
66
  if (parts.length !== 2 || !parts[0] || parts[0].length > 64 || email.length > 254 ||
58
67
  !/^[^\s@<>(),:;"\\]+$/u.test(parts[0]) || parts[0].startsWith('.') || parts[0].endsWith('.') || parts[0].includes('..') ||
59
68
  !/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/i.test(parts[1])) fail('invalid_address');
60
- let name = match?.[1]?.trim();
69
+ name = name?.trim();
61
70
  if (name?.startsWith('"') && name.endsWith('"')) name = name.slice(1, -1);
62
71
  if (name && /[<>"\\]/.test(name)) fail('invalid_address');
63
72
  return name ? { email, name } : { email };
@@ -19,11 +19,12 @@ export function parseHeaders(value) {
19
19
  if (!previous) fail('invalid_inbound_headers');
20
20
  map.set(previous, `${map.get(previous)} ${headerText(line.trim())}`); continue;
21
21
  }
22
- const match = /^([!#$%&'*+.^_`|~0-9A-Za-z-]+):[ \t]*(.*)$/.exec(line);
23
- if (!match) fail('invalid_inbound_headers');
24
- previous = match[1].toLowerCase();
22
+ const colon = line.indexOf(':');
23
+ const name = line.slice(0, colon);
24
+ if (colon < 1 || !/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/.test(name) || /[\u2028\u2029]/.test(line)) fail('invalid_inbound_headers');
25
+ previous = name.toLowerCase();
25
26
  if (map.has(previous) && singleton.has(previous)) fail('duplicate_inbound_header');
26
- const text = headerText(match[2].trim());
27
+ const text = headerText(line.slice(colon + 1).trim());
27
28
  map.set(previous, map.has(previous) ? `${map.get(previous)}, ${text}` : text);
28
29
  }
29
30
  return map;
@@ -130,7 +131,7 @@ export function addresses(value) {
130
131
  export function messageIds(value) {
131
132
  if (value == null || value === '') return [];
132
133
  const source = unfold(value); const ids = source.match(/<[^<>\s]+>/g) ?? [];
133
- if (!ids.length || source.replace(/<[^<>\s]+>/g, '').trim()) fail('invalid_inbound_thread');
134
+ if (!ids.length || !/^(?:<[^<>\s]+>\s*)+$/.test(source)) fail('invalid_inbound_thread');
134
135
  return ids;
135
136
  }
136
137
  export function metadata(headers, from, to, subject) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@runeditrun/rer",
3
- "version": "0.2.32",
3
+ "version": "0.2.33",
4
4
  "description": "The rer command: install, set up, run and launch Run Edit Run checkouts.",
5
5
  "license": "MIT",
6
6
  "type": "module",