@tensile-tools/auth-client 0.0.0-stage → 0.4.1

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.
Files changed (44) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +62 -2
  3. package/dist/client.d.ts +569 -0
  4. package/dist/client.js +637 -0
  5. package/dist/devtools.d.ts +12 -0
  6. package/dist/devtools.js +44 -0
  7. package/dist/elements/account.d.ts +63 -0
  8. package/dist/elements/account.js +331 -0
  9. package/dist/elements/approvals.d.ts +61 -0
  10. package/dist/elements/approvals.js +252 -0
  11. package/dist/elements/auth.d.ts +48 -0
  12. package/dist/elements/auth.js +238 -0
  13. package/dist/elements/base.d.ts +176 -0
  14. package/dist/elements/base.js +540 -0
  15. package/dist/elements/config.d.ts +70 -0
  16. package/dist/elements/config.js +119 -0
  17. package/dist/elements/format.d.ts +32 -0
  18. package/dist/elements/format.js +67 -0
  19. package/dist/elements/index.d.ts +21 -0
  20. package/dist/elements/index.js +31 -0
  21. package/dist/elements/qr.d.ts +9 -0
  22. package/dist/elements/qr.js +302 -0
  23. package/dist/elements/returnto.d.ts +20 -0
  24. package/dist/elements/returnto.js +76 -0
  25. package/dist/elements/setup.d.ts +70 -0
  26. package/dist/elements/setup.js +316 -0
  27. package/dist/elements/styles.d.ts +3 -0
  28. package/dist/elements/styles.js +194 -0
  29. package/dist/elements/text.d.ts +21 -0
  30. package/dist/elements/text.js +302 -0
  31. package/dist/fonts/OFL-geist-mono.txt +93 -0
  32. package/dist/fonts/OFL-geist.txt +93 -0
  33. package/dist/fonts/OFL-inter.txt +93 -0
  34. package/dist/fonts/README.md +18 -0
  35. package/dist/fonts/geist-mono.woff2 +0 -0
  36. package/dist/fonts/geist.woff2 +0 -0
  37. package/dist/fonts/inter.woff2 +0 -0
  38. package/dist/index.d.ts +4 -0
  39. package/dist/index.js +5 -0
  40. package/dist/problem.d.ts +54 -0
  41. package/dist/problem.js +40 -0
  42. package/dist/webauthn.d.ts +46 -0
  43. package/dist/webauthn.js +102 -0
  44. package/package.json +51 -4
@@ -0,0 +1,119 @@
1
+ // The options every element reads, with the defaults in options.md, and
2
+ // how attributes, properties, and configure() combine. This module has no
3
+ // DOM, so the tests run it in Node.
4
+ export const defaults = Object.freeze({
5
+ methods: 'both',
6
+ first: 'passkey',
7
+ autofill: true,
8
+ appName: 'Acme',
9
+ logo: 'none',
10
+ logoSrc: '',
11
+ accent: 'ink',
12
+ radius: 'round',
13
+ font: 'geist',
14
+ theme: 'light',
15
+ density: 'comfortable',
16
+ headline: 'sentence',
17
+ sessions: true,
18
+ agents: true,
19
+ activity: true,
20
+ twoStep: true,
21
+ recoveryCodes: true,
22
+ headlineText: '',
23
+ passkeyLabel: '',
24
+ passwordLabel: '',
25
+ signUpLabel: '',
26
+ text: {},
27
+ });
28
+ /** The option names. */
29
+ export const optionNames = Object.keys(defaults);
30
+ const choices = {
31
+ methods: ['passkey', 'password', 'both'],
32
+ first: ['passkey', 'password'],
33
+ logo: ['none', 'letter', 'image'],
34
+ radius: ['sharp', 'soft', 'round'],
35
+ font: ['geist', 'tight', 'serif', 'system'],
36
+ theme: ['light', 'dark', 'auto'],
37
+ density: ['comfortable', 'compact'],
38
+ headline: ['sentence', 'title'],
39
+ };
40
+ /** `appName` → `app-name`. */
41
+ export const attrName = (k) => k.replace(/[A-Z]/g, c => '-' + c.toLowerCase());
42
+ /** `app-name` → `appName`. */
43
+ export const propName = (a) => a.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
44
+ /**
45
+ * Reads one option from an attribute value. A boolean attribute is true
46
+ * when present, unless its value is `false`, `0`, or `off`. `text` takes
47
+ * JSON. A value that isn't one of the choices is ignored.
48
+ */
49
+ export function fromAttr(k, v) {
50
+ if (v === null)
51
+ return undefined;
52
+ const d = defaults[k];
53
+ if (typeof d === 'boolean')
54
+ return !['false', '0', 'off', 'no'].includes(v.trim().toLowerCase());
55
+ if (k === 'text') {
56
+ try {
57
+ const o = JSON.parse(v);
58
+ return o && typeof o === 'object' ? o : undefined;
59
+ }
60
+ catch {
61
+ return undefined;
62
+ }
63
+ }
64
+ return v;
65
+ }
66
+ /**
67
+ * Merges layers of options, lowest first, and checks each value: a value
68
+ * of the wrong type, an unknown choice, or an accent that isn't a hex
69
+ * colour falls back to the layer below. `text` merges key by key.
70
+ */
71
+ export function resolve(...layers) {
72
+ const out = { ...defaults, text: {} };
73
+ for (const layer of layers) {
74
+ if (!layer)
75
+ continue;
76
+ for (const k of optionNames) {
77
+ const v = layer[k];
78
+ if (v === undefined || v === null)
79
+ continue;
80
+ const d = defaults[k];
81
+ if (k === 'text') {
82
+ if (typeof v === 'object') {
83
+ for (const [tk, tv] of Object.entries(v))
84
+ if (typeof tv === 'string')
85
+ out.text[tk] = tv;
86
+ }
87
+ continue;
88
+ }
89
+ if (typeof d === 'boolean') {
90
+ if (typeof v === 'boolean')
91
+ out[k] = v;
92
+ continue;
93
+ }
94
+ if (typeof v !== 'string')
95
+ continue;
96
+ if (choices[k] && !choices[k].includes(v))
97
+ continue;
98
+ if (k === 'accent' && v !== 'ink' && !isHex(v))
99
+ continue;
100
+ out[k] = v;
101
+ }
102
+ }
103
+ return out;
104
+ }
105
+ /** Reports whether s is a hex colour of 3 or 6 digits. */
106
+ export const isHex = (s) => /^#(?:[0-9a-f]{3}){1,2}$/i.test(s);
107
+ /** The text colour on an accent: white or near-black, whichever has the better contrast. */
108
+ export function onAccent(hex) {
109
+ let h = hex.replace('#', '');
110
+ if (h.length === 3)
111
+ h = [...h].map(c => c + c).join('');
112
+ const [r, g, b] = (h.match(/.{2}/g) ?? ['00', '00', '00']).map(x => {
113
+ const c = parseInt(x, 16) / 255;
114
+ return c <= 0.03928 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
115
+ });
116
+ const lum = 0.2126 * r + 0.7152 * g + 0.0722 * b;
117
+ const nearBlack = 0.0056; // the relative luminance of #111
118
+ return 1.05 / (lum + 0.05) >= (lum + 0.05) / (nearBlack + 0.05) ? '#fff' : '#111';
119
+ }
@@ -0,0 +1,32 @@
1
+ /** 14:32 or 2:32 PM, in the person's locale and time zone, without a leading zero on the hour. */
2
+ export declare function clock(at: Date | string, locale?: string): string;
3
+ /** When something was last used: a text key and its values. */
4
+ export declare function lastUsed(at: Date | string, now: Date, locale?: string): {
5
+ key: string;
6
+ vars: Record<string, string | number>;
7
+ };
8
+ /** When an event happened: today, yesterday, or a date, with the time. */
9
+ export declare function when(at: Date | string, now: Date, locale?: string): {
10
+ key: string;
11
+ vars: Record<string, string>;
12
+ };
13
+ /** An amount split for display: the currency sign and the number. */
14
+ export interface Amount {
15
+ sign: string;
16
+ number: string;
17
+ /** The whole amount as one string, for screen readers and the lead. */
18
+ text: string;
19
+ }
20
+ /**
21
+ * Formats a decimal amount, such as "31.40", in an ISO 4217 currency.
22
+ * It returns undefined for anything that isn't a plain decimal or a known
23
+ * currency, so the caller shows the summary instead.
24
+ */
25
+ export declare function amount(value: string | undefined, currency?: string, locale?: string): Amount | undefined;
26
+ /**
27
+ * Turns an action's summary into the end of "Claude Code wants to …":
28
+ * "Delete the repository acme/api" becomes "delete the repository
29
+ * acme/api.". A summary that starts with a name or an acronym keeps its
30
+ * capital.
31
+ */
32
+ export declare function asAction(summary: string): string;
@@ -0,0 +1,67 @@
1
+ // Times, amounts, and summaries as the elements show them. This module has
2
+ // no DOM, so the tests run it in Node.
3
+ /** 14:32 or 2:32 PM, in the person's locale and time zone, without a leading zero on the hour. */
4
+ export function clock(at, locale) {
5
+ return new Date(at).toLocaleTimeString(locale, { hour: 'numeric', minute: '2-digit' });
6
+ }
7
+ const minute = 60_000;
8
+ /** When something was last used: a text key and its values. */
9
+ export function lastUsed(at, now, locale) {
10
+ const t = new Date(at);
11
+ const ago = now.getTime() - t.getTime();
12
+ if (ago < 2 * minute)
13
+ return { key: 'time.now', vars: {} };
14
+ if (ago < 60 * minute)
15
+ return { key: 'time.minutes', vars: { count: Math.floor(ago / minute) } };
16
+ if (sameDay(t, now))
17
+ return { key: 'time.hours', vars: { count: Math.floor(ago / (60 * minute)) } };
18
+ if (sameDay(t, new Date(now.getTime() - 24 * 60 * minute)))
19
+ return { key: 'time.yesterday', vars: {} };
20
+ return { key: 'time.on', vars: { date: t.toLocaleDateString(locale, { day: 'numeric', month: 'short' }) } };
21
+ }
22
+ /** When an event happened: today, yesterday, or a date, with the time. */
23
+ export function when(at, now, locale) {
24
+ const t = new Date(at);
25
+ const time = clock(t, locale);
26
+ if (sameDay(t, now))
27
+ return { key: 'time.today', vars: { time } };
28
+ if (sameDay(t, new Date(now.getTime() - 24 * 60 * minute)))
29
+ return { key: 'time.yesterdayAt', vars: { time } };
30
+ return { key: 'time.dateAt', vars: { date: t.toLocaleDateString(locale, { day: 'numeric', month: 'short', ...(t.getFullYear() === now.getFullYear() ? {} : { year: 'numeric' }) }), time } };
31
+ }
32
+ function sameDay(a, b) {
33
+ return a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate();
34
+ }
35
+ /**
36
+ * Formats a decimal amount, such as "31.40", in an ISO 4217 currency.
37
+ * It returns undefined for anything that isn't a plain decimal or a known
38
+ * currency, so the caller shows the summary instead.
39
+ */
40
+ export function amount(value, currency = 'USD', locale) {
41
+ if (!value || !/^\d{1,15}(\.\d{1,4})?$/.test(value))
42
+ return undefined;
43
+ let f;
44
+ try {
45
+ const decimals = value.includes('.') ? value.split('.')[1].length : 0;
46
+ f = new Intl.NumberFormat(locale, { style: 'currency', currency, minimumFractionDigits: decimals, maximumFractionDigits: Math.max(decimals, 2) });
47
+ }
48
+ catch {
49
+ return undefined;
50
+ }
51
+ const parts = f.formatToParts(Number(value));
52
+ const sign = parts.filter(p => p.type === 'currency').map(p => p.value).join('');
53
+ const number = parts.filter(p => p.type !== 'currency' && p.type !== 'literal').map(p => p.value).join('');
54
+ return { sign, number, text: f.format(Number(value)) };
55
+ }
56
+ /**
57
+ * Turns an action's summary into the end of "Claude Code wants to …":
58
+ * "Delete the repository acme/api" becomes "delete the repository
59
+ * acme/api.". A summary that starts with a name or an acronym keeps its
60
+ * capital.
61
+ */
62
+ export function asAction(summary) {
63
+ let s = summary.trim();
64
+ if (/^[A-Z][a-z]/.test(s) && !/^[A-Z][a-z]+[A-Z]/.test(s))
65
+ s = s[0].toLowerCase() + s.slice(1);
66
+ return /[.!?”]$/.test(s) ? s : s + '.';
67
+ }
@@ -0,0 +1,21 @@
1
+ import { Approval, Approvals } from './approvals.ts';
2
+ import { ActivityLog, Sessions, WasntMe } from './account.ts';
3
+ import { SignIn, SignUp, StepUp } from './auth.ts';
4
+ import { RecoveryCodes, TwoStep } from './setup.ts';
5
+ export { configure, type GlobalConfig, TensileElement } from './base.ts';
6
+ export { defaults, type Options } from './config.ts';
7
+ export { english } from './text.ts';
8
+ export { ActivityLog, Approval, Approvals, RecoveryCodes, Sessions, SignIn, SignUp, StepUp, TwoStep, WasntMe };
9
+ /** The tag name of each element. */
10
+ export declare const elements: {
11
+ readonly 'tensile-sign-in': typeof SignIn;
12
+ readonly 'tensile-sign-up': typeof SignUp;
13
+ readonly 'tensile-step-up': typeof StepUp;
14
+ readonly 'tensile-approval': typeof Approval;
15
+ readonly 'tensile-approvals': typeof Approvals;
16
+ readonly 'tensile-sessions': typeof Sessions;
17
+ readonly 'tensile-wasnt-me': typeof WasntMe;
18
+ readonly 'tensile-activity': typeof ActivityLog;
19
+ readonly 'tensile-two-step': typeof TwoStep;
20
+ readonly 'tensile-recovery-codes': typeof RecoveryCodes;
21
+ };
@@ -0,0 +1,31 @@
1
+ // The elements: drop-in sign-in and account screens built on the browser
2
+ // client. Importing this module defines every element:
3
+ //
4
+ // <script type="module" src="/auth/client/elements/index.js"></script>
5
+ // <tensile-sign-in app-name="Acme" redirect="/"></tensile-sign-in>
6
+ import { Approval, Approvals } from "./approvals.js";
7
+ import { ActivityLog, Sessions, WasntMe } from "./account.js";
8
+ import { SignIn, SignUp, StepUp } from "./auth.js";
9
+ import { RecoveryCodes, TwoStep } from "./setup.js";
10
+ export { configure, TensileElement } from "./base.js";
11
+ export { defaults } from "./config.js";
12
+ export { english } from "./text.js";
13
+ export { ActivityLog, Approval, Approvals, RecoveryCodes, Sessions, SignIn, SignUp, StepUp, TwoStep, WasntMe };
14
+ /** The tag name of each element. */
15
+ export const elements = {
16
+ 'tensile-sign-in': SignIn,
17
+ 'tensile-sign-up': SignUp,
18
+ 'tensile-step-up': StepUp,
19
+ 'tensile-approval': Approval,
20
+ 'tensile-approvals': Approvals,
21
+ 'tensile-sessions': Sessions,
22
+ 'tensile-wasnt-me': WasntMe,
23
+ 'tensile-activity': ActivityLog,
24
+ 'tensile-two-step': TwoStep,
25
+ 'tensile-recovery-codes': RecoveryCodes,
26
+ };
27
+ if (typeof customElements !== 'undefined') {
28
+ for (const [tag, cls] of Object.entries(elements))
29
+ if (!customElements.get(tag))
30
+ customElements.define(tag, cls);
31
+ }
@@ -0,0 +1,9 @@
1
+ /** A QR code: `size` modules square, `dark[y][x]` true for a dark module. */
2
+ export interface QR {
3
+ size: number;
4
+ dark: boolean[][];
5
+ }
6
+ /** Encodes text as UTF-8 bytes. It throws when the text is too long for version 15. */
7
+ export declare function encodeQR(text: string): QR;
8
+ /** Draws q as one SVG path, one unit per module, with a 4-module quiet zone. */
9
+ export declare function qrPath(q: QR): string;
@@ -0,0 +1,302 @@
1
+ // A QR code encoder for the authenticator setup: byte mode, error
2
+ // correction level M, versions 1 to 15, and the mask with the lowest
3
+ // penalty. It follows the reference algorithm of Project Nayuki's QR Code
4
+ // generator (MIT), cut to what an otpauth:// URI needs.
5
+ // Error correction codewords per block and blocks, at level M, by version.
6
+ const eccPerBlock = [-1, 10, 16, 26, 18, 24, 16, 18, 22, 22, 26, 30, 22, 22, 24, 24];
7
+ const blocks = [-1, 1, 1, 1, 2, 2, 4, 4, 4, 5, 5, 5, 8, 9, 9, 10];
8
+ const maxVersion = 15;
9
+ function rawModules(ver) {
10
+ let n = (16 * ver + 128) * ver + 64;
11
+ if (ver >= 2) {
12
+ const align = Math.floor(ver / 7) + 2;
13
+ n -= (25 * align - 10) * align - 55;
14
+ if (ver >= 7)
15
+ n -= 36;
16
+ }
17
+ return n;
18
+ }
19
+ const dataCodewords = (ver) => Math.floor(rawModules(ver) / 8) - eccPerBlock[ver] * blocks[ver];
20
+ function gfMul(x, y) {
21
+ let z = 0;
22
+ for (let i = 7; i >= 0; i--) {
23
+ z = (z << 1) ^ ((z >>> 7) * 0x11d);
24
+ z ^= ((y >>> i) & 1) * x;
25
+ }
26
+ return z;
27
+ }
28
+ function divisor(degree) {
29
+ const out = new Array(degree).fill(0);
30
+ out[degree - 1] = 1;
31
+ let root = 1;
32
+ for (let i = 0; i < degree; i++) {
33
+ for (let j = 0; j < degree; j++) {
34
+ out[j] = gfMul(out[j], root);
35
+ if (j + 1 < degree)
36
+ out[j] ^= out[j + 1];
37
+ }
38
+ root = gfMul(root, 0x02);
39
+ }
40
+ return out;
41
+ }
42
+ function remainder(data, div) {
43
+ const out = new Array(div.length).fill(0);
44
+ for (const b of data) {
45
+ const factor = b ^ out.shift();
46
+ out.push(0);
47
+ div.forEach((c, i) => { out[i] ^= gfMul(c, factor); });
48
+ }
49
+ return out;
50
+ }
51
+ function alignmentPositions(ver) {
52
+ if (ver === 1)
53
+ return [];
54
+ const n = Math.floor(ver / 7) + 2;
55
+ const step = Math.ceil((ver * 4 + 4) / (n * 2 - 2)) * 2;
56
+ const out = [6];
57
+ for (let pos = ver * 4 + 17 - 7; out.length < n; pos -= step)
58
+ out.splice(1, 0, pos);
59
+ return out;
60
+ }
61
+ const bit = (x, i) => ((x >>> i) & 1) !== 0;
62
+ /** Encodes text as UTF-8 bytes. It throws when the text is too long for version 15. */
63
+ export function encodeQR(text) {
64
+ const bytes = [...new TextEncoder().encode(text)];
65
+ let ver = 1;
66
+ for (; ver <= maxVersion; ver++) {
67
+ if (4 + (ver < 10 ? 8 : 16) + bytes.length * 8 <= dataCodewords(ver) * 8)
68
+ break;
69
+ }
70
+ if (ver > maxVersion)
71
+ throw new RangeError('qr: the text is too long');
72
+ // Data bits: byte mode, the count, the bytes, a terminator, and padding.
73
+ const bits = [];
74
+ const put = (v, n) => { for (let i = n - 1; i >= 0; i--)
75
+ bits.push((v >>> i) & 1); };
76
+ put(4, 4);
77
+ put(bytes.length, ver < 10 ? 8 : 16);
78
+ for (const b of bytes)
79
+ put(b, 8);
80
+ const cap = dataCodewords(ver) * 8;
81
+ put(0, Math.min(4, cap - bits.length));
82
+ put(0, (8 - (bits.length % 8)) % 8);
83
+ for (let pad = 0xec; bits.length < cap; pad ^= 0xec ^ 0x11)
84
+ put(pad, 8);
85
+ const data = [];
86
+ for (let i = 0; i < bits.length; i += 8)
87
+ data.push(bits.slice(i, i + 8).reduce((a, b) => (a << 1) | b, 0));
88
+ // Error correction, in blocks, interleaved.
89
+ const nBlocks = blocks[ver];
90
+ const eccLen = eccPerBlock[ver];
91
+ const raw = Math.floor(rawModules(ver) / 8);
92
+ const nShort = nBlocks - (raw % nBlocks);
93
+ const shortLen = Math.floor(raw / nBlocks);
94
+ const div = divisor(eccLen);
95
+ const parts = [];
96
+ for (let i = 0, k = 0; i < nBlocks; i++) {
97
+ const dat = data.slice(k, k + shortLen - eccLen + (i < nShort ? 0 : 1));
98
+ k += dat.length;
99
+ const ecc = remainder(dat, div);
100
+ if (i < nShort)
101
+ dat.push(0);
102
+ parts.push(dat.concat(ecc));
103
+ }
104
+ const codewords = [];
105
+ for (let i = 0; i < parts[0].length; i++) {
106
+ parts.forEach((p, j) => { if (i !== shortLen - eccLen || j >= nShort)
107
+ codewords.push(p[i]); });
108
+ }
109
+ // Function patterns.
110
+ const size = ver * 4 + 17;
111
+ const dark = Array.from({ length: size }, () => new Array(size).fill(false));
112
+ const fixed = Array.from({ length: size }, () => new Array(size).fill(false));
113
+ const set = (x, y, on) => { dark[y][x] = on; fixed[y][x] = true; };
114
+ for (let i = 0; i < size; i++) {
115
+ set(6, i, i % 2 === 0);
116
+ set(i, 6, i % 2 === 0);
117
+ }
118
+ for (const [cx, cy] of [[3, 3], [size - 4, 3], [3, size - 4]]) {
119
+ for (let dy = -4; dy <= 4; dy++) {
120
+ for (let dx = -4; dx <= 4; dx++) {
121
+ const d = Math.max(Math.abs(dx), Math.abs(dy));
122
+ const x = cx + dx, y = cy + dy;
123
+ if (x >= 0 && x < size && y >= 0 && y < size)
124
+ set(x, y, d !== 2 && d !== 4);
125
+ }
126
+ }
127
+ }
128
+ const al = alignmentPositions(ver);
129
+ al.forEach((ax, i) => al.forEach((ay, j) => {
130
+ if ((i === 0 && j === 0) || (i === 0 && j === al.length - 1) || (i === al.length - 1 && j === 0))
131
+ return;
132
+ for (let dy = -2; dy <= 2; dy++)
133
+ for (let dx = -2; dx <= 2; dx++)
134
+ set(ax + dx, ay + dy, Math.max(Math.abs(dx), Math.abs(dy)) !== 1);
135
+ }));
136
+ const format = (mask) => {
137
+ const d = mask; // level M is 0b00
138
+ let rem = d;
139
+ for (let i = 0; i < 10; i++)
140
+ rem = (rem << 1) ^ ((rem >>> 9) * 0x537);
141
+ const b = ((d << 10) | rem) ^ 0x5412;
142
+ for (let i = 0; i <= 5; i++)
143
+ set(8, i, bit(b, i));
144
+ set(8, 7, bit(b, 6));
145
+ set(8, 8, bit(b, 7));
146
+ set(7, 8, bit(b, 8));
147
+ for (let i = 9; i < 15; i++)
148
+ set(14 - i, 8, bit(b, i));
149
+ for (let i = 0; i < 8; i++)
150
+ set(size - 1 - i, 8, bit(b, i));
151
+ for (let i = 8; i < 15; i++)
152
+ set(8, size - 15 + i, bit(b, i));
153
+ set(8, size - 8, true);
154
+ };
155
+ format(0);
156
+ if (ver >= 7) {
157
+ let rem = ver;
158
+ for (let i = 0; i < 12; i++)
159
+ rem = (rem << 1) ^ ((rem >>> 11) * 0x1f25);
160
+ const b = (ver << 12) | rem;
161
+ for (let i = 0; i < 18; i++) {
162
+ const a = size - 11 + (i % 3), c = Math.floor(i / 3);
163
+ set(a, c, bit(b, i));
164
+ set(c, a, bit(b, i));
165
+ }
166
+ }
167
+ // Codewords, in the zigzag.
168
+ let i = 0;
169
+ for (let right = size - 1; right >= 1; right -= 2) {
170
+ if (right === 6)
171
+ right = 5;
172
+ for (let vert = 0; vert < size; vert++) {
173
+ for (let j = 0; j < 2; j++) {
174
+ const x = right - j;
175
+ const y = ((right + 1) & 2) === 0 ? size - 1 - vert : vert;
176
+ if (!fixed[y][x] && i < codewords.length * 8) {
177
+ dark[y][x] = bit(codewords[i >>> 3], 7 - (i & 7));
178
+ i++;
179
+ }
180
+ }
181
+ }
182
+ }
183
+ // The mask with the lowest penalty.
184
+ const flip = (mask) => {
185
+ for (let y = 0; y < size; y++) {
186
+ for (let x = 0; x < size; x++) {
187
+ if (fixed[y][x])
188
+ continue;
189
+ let inv;
190
+ switch (mask) {
191
+ case 0:
192
+ inv = (x + y) % 2 === 0;
193
+ break;
194
+ case 1:
195
+ inv = y % 2 === 0;
196
+ break;
197
+ case 2:
198
+ inv = x % 3 === 0;
199
+ break;
200
+ case 3:
201
+ inv = (x + y) % 3 === 0;
202
+ break;
203
+ case 4:
204
+ inv = (Math.floor(x / 3) + Math.floor(y / 2)) % 2 === 0;
205
+ break;
206
+ case 5:
207
+ inv = ((x * y) % 2) + ((x * y) % 3) === 0;
208
+ break;
209
+ case 6:
210
+ inv = (((x * y) % 2) + ((x * y) % 3)) % 2 === 0;
211
+ break;
212
+ default: inv = (((x + y) % 2) + ((x * y) % 3)) % 2 === 0;
213
+ }
214
+ if (inv)
215
+ dark[y][x] = !dark[y][x];
216
+ }
217
+ }
218
+ };
219
+ let best = 0;
220
+ let min = Infinity;
221
+ for (let m = 0; m < 8; m++) {
222
+ flip(m);
223
+ format(m);
224
+ const p = penalty(dark, size);
225
+ if (p < min) {
226
+ min = p;
227
+ best = m;
228
+ }
229
+ flip(m);
230
+ }
231
+ flip(best);
232
+ format(best);
233
+ return { size, dark };
234
+ }
235
+ function penalty(m, size) {
236
+ let score = 0;
237
+ const addHistory = (len, h) => {
238
+ if (h[0] === 0)
239
+ len += size;
240
+ h.pop();
241
+ h.unshift(len);
242
+ };
243
+ const count = (h) => {
244
+ const n = h[1];
245
+ const core = n > 0 && h[2] === n && h[3] === n * 3 && h[4] === n && h[5] === n;
246
+ return (core && h[0] >= n * 4 && h[6] >= n ? 1 : 0) + (core && h[6] >= n * 4 && h[0] >= n ? 1 : 0);
247
+ };
248
+ const line = (get) => {
249
+ let color = false;
250
+ let run = 0;
251
+ const h = [0, 0, 0, 0, 0, 0, 0];
252
+ for (let i = 0; i < size; i++) {
253
+ if (get(i) === color) {
254
+ run++;
255
+ if (run === 5)
256
+ score += 3;
257
+ else if (run > 5)
258
+ score++;
259
+ }
260
+ else {
261
+ addHistory(run, h);
262
+ if (!color)
263
+ score += count(h) * 40;
264
+ color = get(i);
265
+ run = 1;
266
+ }
267
+ }
268
+ if (color) {
269
+ addHistory(run, h);
270
+ run = 0;
271
+ }
272
+ run += size;
273
+ addHistory(run, h);
274
+ score += count(h) * 40;
275
+ };
276
+ for (let y = 0; y < size; y++)
277
+ line(x => m[y][x]);
278
+ for (let x = 0; x < size; x++)
279
+ line(y => m[y][x]);
280
+ let darkCount = 0;
281
+ for (let y = 0; y < size; y++) {
282
+ for (let x = 0; x < size; x++) {
283
+ if (m[y][x])
284
+ darkCount++;
285
+ if (y < size - 1 && x < size - 1) {
286
+ const c = m[y][x];
287
+ if (c === m[y][x + 1] && c === m[y + 1][x] && c === m[y + 1][x + 1])
288
+ score += 3;
289
+ }
290
+ }
291
+ }
292
+ const total = size * size;
293
+ score += (Math.ceil(Math.abs(darkCount * 20 - total * 10) / total) - 1) * 10;
294
+ return score;
295
+ }
296
+ /** Draws q as one SVG path, one unit per module, with a 4-module quiet zone. */
297
+ export function qrPath(q) {
298
+ let d = '';
299
+ q.dark.forEach((row, y) => row.forEach((on, x) => { if (on)
300
+ d += `M${x + 4} ${y + 4}h1v1h-1z`; }));
301
+ return d;
302
+ }
@@ -0,0 +1,20 @@
1
+ /** The query parameter that carries the path to go back to after sign-in. */
2
+ export declare const returnToParam = "return_to";
3
+ /**
4
+ * `s` when sign-in may send the browser there, or undefined: a path that
5
+ * starts with one `/`, with no scheme, host, or fragment, no backslash,
6
+ * space, or control character, no decoded path that starts with `//`, no
7
+ * `.` or `..` segment, plain or percent-encoded, and at most 2048
8
+ * characters. A URL parser removes dot segments, so `/.//evil.example`
9
+ * would resolve to `//evil.example`, another host. It matches
10
+ * authhttp.SafeReturnTo.
11
+ */
12
+ export declare function safeReturnTo(s: string | null | undefined): string | undefined;
13
+ /** The safe return-to path in a query string such as `location.search`, or undefined. */
14
+ export declare function returnToFrom(search: string): string | undefined;
15
+ /** `href` with `back` as its return-to path, or `href` alone when `back` isn't safe. */
16
+ export declare function withReturnTo(href: string, back: string | undefined): string;
17
+ /** Where to go after sign-in: the safe `return_to` of this page's URL, as an absolute URL on this origin, or undefined. */
18
+ export declare function returnToHere(): string | undefined;
19
+ /** `href` carrying this page's own `return_to` on, for a link between sign-in and sign-up. */
20
+ export declare function carryReturnTo(href: string): string;
@@ -0,0 +1,76 @@
1
+ // The return-to path: where sign-in sends a person back to, for example
2
+ // the approval page they opened while signed out. It is always a
3
+ // relative path on this origin, never a URL, so no page can use it to
4
+ // send a person to another site.
5
+ /** The query parameter that carries the path to go back to after sign-in. */
6
+ export const returnToParam = 'return_to';
7
+ const maxReturnTo = 2048;
8
+ /**
9
+ * `s` when sign-in may send the browser there, or undefined: a path that
10
+ * starts with one `/`, with no scheme, host, or fragment, no backslash,
11
+ * space, or control character, no decoded path that starts with `//`, no
12
+ * `.` or `..` segment, plain or percent-encoded, and at most 2048
13
+ * characters. A URL parser removes dot segments, so `/.//evil.example`
14
+ * would resolve to `//evil.example`, another host. It matches
15
+ * authhttp.SafeReturnTo.
16
+ */
17
+ export function safeReturnTo(s) {
18
+ if (!s || s.length > maxReturnTo || s[0] !== '/' || s.startsWith('//') || s.startsWith('/\\'))
19
+ return undefined;
20
+ if (/[\u0000- \u007f\\#]/.test(s))
21
+ return undefined;
22
+ const raw = s.split('?')[0];
23
+ let path;
24
+ try {
25
+ path = decodeURIComponent(raw);
26
+ }
27
+ catch {
28
+ return undefined;
29
+ }
30
+ if (path.startsWith('//') || path.startsWith('/\\') || /[\\\r\n]/.test(path))
31
+ return undefined;
32
+ if (hasDotSegment(raw) || hasDotSegment(path))
33
+ return undefined;
34
+ try {
35
+ const base = 'https://origin.invalid';
36
+ if (new URL(s, base).origin !== base)
37
+ return undefined;
38
+ }
39
+ catch {
40
+ return undefined;
41
+ }
42
+ return s;
43
+ }
44
+ /** Whether `p` has a `.` or `..` segment, where `%2e` and `%2E` count as `.`. */
45
+ function hasDotSegment(p) {
46
+ return p.split('/').some(seg => {
47
+ const d = seg.replace(/%2e/gi, '.');
48
+ return d === '.' || d === '..';
49
+ });
50
+ }
51
+ /** The safe return-to path in a query string such as `location.search`, or undefined. */
52
+ export function returnToFrom(search) {
53
+ return safeReturnTo(new URLSearchParams(search).get(returnToParam));
54
+ }
55
+ /** `href` with `back` as its return-to path, or `href` alone when `back` isn't safe. */
56
+ export function withReturnTo(href, back) {
57
+ const path = safeReturnTo(back);
58
+ if (!path)
59
+ return href;
60
+ const u = new URL(href);
61
+ u.searchParams.set(returnToParam, path);
62
+ return u.href;
63
+ }
64
+ /** Where to go after sign-in: the safe `return_to` of this page's URL, as an absolute URL on this origin, or undefined. */
65
+ export function returnToHere() {
66
+ if (typeof location === 'undefined')
67
+ return undefined;
68
+ const back = returnToFrom(location.search);
69
+ return back ? new URL(back, location.origin).href : undefined;
70
+ }
71
+ /** `href` carrying this page's own `return_to` on, for a link between sign-in and sign-up. */
72
+ export function carryReturnTo(href) {
73
+ if (typeof location === 'undefined')
74
+ return href;
75
+ return withReturnTo(href, returnToFrom(location.search));
76
+ }