1 Commits
Author SHA1 Message Date
Anya Tokugawa 9dd425f765 Fix UUID generation in browsers without crypto.randomUUID
Release container images / release (push) Successful in 18s
Build and publish container images / images (push) Successful in 7m55s
2026-09-29 12:39:58 +09:00
5 changed files with 172 additions and 0 deletions

No files matched your search

+45
View File
@@ -0,0 +1,45 @@
window.addEventListener('load', async () => {
const wait = async check => {
for (let i = 0; i < 100; i++) {
if (await check()) return;
await new Promise(resolve => setTimeout(resolve, 50));
}
throw new Error('Timed out: ' + check);
};
const api = '/_/api/v1/extension/organizer.tasks/items';
try {
if (!window.uuidNativeWasMissing) throw new Error('Missing native UUID fixture was not applied');
if (typeof crypto.randomUUID !== 'function') throw new Error('UUID fallback not loaded');
document.getElementById('tasks-new').click();
const dialog = document.getElementById('tasks-dialog');
await wait(() => dialog.open && dialog.querySelector('[name=title]'));
const title = dialog.querySelector('[name=title]');
title.value = 'HTTP compatibility project';
title.dispatchEvent(new Event('input', {bubbles:true}));
document.getElementById('tasks-form').requestSubmit();
await wait(() => !dialog.open);
const response = await fetch(api + '?kind=project');
if (!response.ok) throw new Error('Project query failed');
const project = (await response.json()).items.find(item => item.title === title.value);
if (!project || !/^[0-9a-f-]{14}4[0-9a-f-]{21}$/.test(project.uuid)) throw new Error('Project not saved with UUID v4');
if (!document.getElementById('tasks-list').textContent.includes(project.title)) throw new Error('Saved project not listed');
const frame = document.createElement('iframe');
frame.src = '/v/plan/project/' + project.uuid;
document.body.append(frame);
await wait(() => frame.contentDocument?.getElementById('tasks-quick-title') && frame.contentDocument.readyState === 'complete');
const doc = frame.contentDocument;
if (!frame.contentWindow.uuidNativeWasMissing) throw new Error('Task fallback fixture was not applied');
doc.getElementById('tasks-quick-title').value = 'HTTP compatibility task';
doc.getElementById('tasks-capture').requestSubmit();
await wait(() => Array.from(doc.querySelectorAll('[name=title]')).some(input => input.value === 'HTTP compatibility task'));
const tasks = await fetch(api + '?project=' + project.uuid).then(r => r.json());
if (!tasks.items.some(item => item.title === 'HTTP compatibility task' && item.project_uuid === project.uuid)) throw new Error('Task not saved in project');
document.body.dataset.vimReady = '1';
} catch (error) {
const output = document.createElement('pre');
output.id = 'error';
output.textContent = error.stack || error.message;
document.body.append(output);
}
});
+47
View File
@@ -0,0 +1,47 @@
const assert = require('node:assert/strict');
const {readFileSync} = require('node:fs');
const {webcrypto} = require('node:crypto');
const vm = require('node:vm');
const script = readFileSync('static/js/uuid.js', 'utf8');
const run = crypto => { const context = vm.createContext({crypto}); vm.runInContext(script, context); return context; };
const native = () => 'native';
const supported = {randomUUID: native};
run(supported);
assert.equal(supported.randomUUID, native, 'do not replace native implementations');
let calls = 0;
const fallback = {getRandomValues(bytes) {
assert.equal(this, fallback, 'preserve Web Crypto receiver');
assert.equal(bytes.length, 16);
calls++;
bytes.fill(0xff);
return bytes;
}};
const context = run(fallback);
assert.equal(fallback.randomUUID(), 'ffffffff-ffff-4fff-bfff-ffffffffffff');
assert.equal(calls, 1);
const installed = fallback.randomUUID;
vm.runInContext(script, context);
assert.equal(fallback.randomUUID, installed, 'loading twice must be harmless');
const zeros = {getRandomValues: bytes => { bytes.fill(0); return bytes; }};
run(zeros);
assert.equal(zeros.randomUUID(), '00000000-0000-4000-8000-000000000000');
const real = {getRandomValues: bytes => webcrypto.getRandomValues(bytes)};
run(real);
const ids = new Set();
for (let i = 0; i < 10000; i++) {
const id = real.randomUUID();
assert.match(id, /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/);
assert.ok(!ids.has(id), 'unexpected UUID collision');
ids.add(id);
}
const unavailable = {};
run(unavailable);
assert.equal(unavailable.randomUUID, undefined, 'do not fabricate insecure randomness');
run(undefined);
const broken = {getRandomValues() { throw new Error('entropy unavailable'); }};
run(broken);
assert.throws(() => broken.randomUUID(), /entropy unavailable/);
console.log('UUID compatibility: native, fallback, v4 bits, uniqueness and fail-closed checks passed');
+61
View File
@@ -0,0 +1,61 @@
package server
import (
"context"
"net/http"
"net/http/httptest"
"os"
"os/exec"
"strings"
"testing"
"time"
)
func TestUUIDCompatibilityJS(t *testing.T) {
node, err := exec.LookPath("node")
if err != nil {
t.Skip("node is required for UUID compatibility tests")
}
t.Chdir("../..")
if out, err := exec.Command(node, "internal/server/testdata/uuid.test.cjs").CombinedOutput(); err != nil {
t.Fatalf("UUID compatibility: %v\n%s", err, out)
}
}
func TestTaskProjectUUIDFallbackChromium(t *testing.T) {
if os.Getenv("PAGESWIKI_BROWSER_TEST") != "1" {
t.Skip("opt-in Chromium")
}
s, token, _, _ := taskFixture(t)
script, err := os.ReadFile("internal/server/testdata/uuid-project-browser.js")
if err != nil {
t.Fatal(err)
}
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
r.Header.Set("Authorization", "Bearer "+token)
if r.Method == "GET" && strings.HasPrefix(r.URL.Path, "/v/plan/") {
rec := httptest.NewRecorder()
s.withAuthorization(s.mux).ServeHTTP(rec, r)
for key, values := range rec.Header() {
w.Header()[key] = values
}
body := strings.Replace(rec.Body.String(), "<head>", `<head><script>Object.defineProperty(crypto,'randomUUID',{value:undefined,writable:true,configurable:true});window.uuidNativeWasMissing=typeof crypto.randomUUID==='undefined';</script>`, 1)
if r.URL.Path == "/v/plan/projects" {
body = strings.Replace(body, "</body>", "<script>"+string(script)+"</script></body>", 1)
}
w.Header().Del("Content-Length")
w.WriteHeader(rec.Code)
_, _ = w.Write([]byte(body))
return
}
s.withAuthorization(s.mux).ServeHTTP(w, r)
}))
defer server.Close()
ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second)
defer cancel()
target := strings.Replace(server.URL, "127.0.0.1", "localhost", 1) + "/v/plan/projects"
cmd := exec.CommandContext(ctx, "node", "internal/server/testdata/vim-browser-smoke.mjs", target, t.TempDir())
if out, err := cmd.CombinedOutput(); err != nil {
t.Fatalf("project creation without randomUUID: %v\n%s", err, out)
}
}
+18
View File
@@ -0,0 +1,18 @@
// randomUUID is secure-context-only; getRandomValues is also available on HTTP.
// Keep native implementations and never fall back to Math.random for IDs.
(() => {
'use strict';
const crypto = globalThis.crypto;
if (!crypto || typeof crypto.randomUUID === 'function' || typeof crypto.getRandomValues !== 'function') return;
Object.defineProperty(crypto, 'randomUUID', {
configurable: true,
writable: true,
value: function randomUUID() {
const bytes = crypto.getRandomValues(new Uint8Array(16));
bytes[6] = (bytes[6] & 0x0f) | 0x40;
bytes[8] = (bytes[8] & 0x3f) | 0x80;
const hex = Array.from(bytes, byte => byte.toString(16).padStart(2, '0')).join('');
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
},
});
})();
+1
View File
@@ -1,4 +1,5 @@
{{ define "auth-menu" }} {{ define "auth-menu" }}
<script src="/static/js/uuid.js?v=1" defer></script>
<link rel="stylesheet" href="/static/css/notifications.css?v=3"> <link rel="stylesheet" href="/static/css/notifications.css?v=3">
<link rel="stylesheet" href="/static/css/notification-active.css?v=1"> <link rel="stylesheet" href="/static/css/notification-active.css?v=1">
<link rel="stylesheet" href="/static/css/nav-modals.css?v=3"> <link rel="stylesheet" href="/static/css/nav-modals.css?v=3">