@yargote/artifacts-cli 0.1.0-beta.1 → 0.1.0-beta.11
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 +167 -19
- package/package.json +9 -4
- package/skills/artifacts-cli/SKILL.md +80 -0
- package/skills/artifacts-cli/references/commands.md +250 -0
- package/skills/artifacts-cli/references/verify-retained.md +119 -0
- package/skills/artifacts-cli/scripts/prepare-retained.mjs +149 -0
- package/skills/artifacts-design/SKILL.md +92 -0
- package/skills/artifacts-design/THIRD-PARTY-NOTICES.md +155 -0
- package/skills/artifacts-design/fonts/OFL.txt +96 -0
- package/skills/artifacts-design/fonts/bricolage-grotesque.woff2 +0 -0
- package/skills/artifacts-design/fonts/jetbrains-mono.woff2 +0 -0
- package/skills/artifacts-design/fonts/newsreader-italic.woff2 +0 -0
- package/skills/artifacts-design/fonts/newsreader.woff2 +0 -0
- package/skills/artifacts-design/fonts/public-sans-italic.woff2 +0 -0
- package/skills/artifacts-design/fonts/public-sans.woff2 +0 -0
- package/skills/artifacts-design/references/canvas.md +100 -0
- package/skills/artifacts-design/references/catppuccin.md +38 -0
- package/skills/artifacts-design/references/interface-checks.md +60 -0
- package/skills/artifacts-design/references/local-checks.md +70 -0
- package/skills/artifacts-design/references/visual-explanations.md +13 -0
- package/skills/artifacts-design/scripts/embed-fonts.mjs +246 -0
- package/skills/artifacts-design/scripts/verify-local.mjs +333 -0
- package/skills/artifacts-design/templates/starter.html +170 -0
- package/src/auth.d.ts +4 -1
- package/src/auth.js +184 -45
- package/src/credentials.d.ts +2 -0
- package/src/credentials.js +22 -0
- package/src/index.js +153 -31
- package/src/operations.d.ts +155 -38
- package/src/operations.js +11 -1
- package/src/skills.d.ts +9 -0
- package/src/skills.js +181 -0
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
<!doctype html>
|
|
2
|
+
<html lang="es">
|
|
3
|
+
<head>
|
|
4
|
+
<meta charset="utf-8">
|
|
5
|
+
<meta name="viewport" content="width=device-width,initial-scale=1">
|
|
6
|
+
<title>Artifact starter</title>
|
|
7
|
+
<style>
|
|
8
|
+
/* Layout: one centered column; summary before detail, then the dominant table, chart, or diagram. */
|
|
9
|
+
:root{
|
|
10
|
+
--page:#eff1f5; --surface:#ffffff; --sunken:#e6e9ef; --line:#ccd0da; --control:#8c8fa1;
|
|
11
|
+
--fg:#4c4f69; --muted:#5c5f77; --accent:#1e66f5; --on-accent:#ffffff; --accent-ink:#1957d0;
|
|
12
|
+
--ok:#40a02b; --ok-ink:#307820; --warn:#df8e1d; --warn-ink:#915c13; --bad:#d20f39; --bad-ink:#b20d30;
|
|
13
|
+
--neutral-soft:color-mix(in srgb,var(--fg) 9%,var(--surface));
|
|
14
|
+
--accent-soft:color-mix(in srgb,var(--accent) 14%,var(--surface));
|
|
15
|
+
--ok-soft:color-mix(in srgb,var(--ok) 14%,var(--surface));
|
|
16
|
+
--warn-soft:color-mix(in srgb,var(--warn) 14%,var(--surface));
|
|
17
|
+
--bad-soft:color-mix(in srgb,var(--bad) 14%,var(--surface));
|
|
18
|
+
--f-display:"Bricolage Grotesque","Avenir Next",system-ui,sans-serif;
|
|
19
|
+
--f-body:"Public Sans","Segoe UI",system-ui,sans-serif;
|
|
20
|
+
--f-mono:"JetBrains Mono",ui-monospace,"SF Mono",Menlo,Consolas,monospace;
|
|
21
|
+
--radius:10px; --width:1120px;
|
|
22
|
+
color-scheme:light;
|
|
23
|
+
}
|
|
24
|
+
@media (prefers-color-scheme:dark){:root:not([data-theme="light"]){
|
|
25
|
+
--page:#181825; --surface:#1e1e2e; --sunken:#11111b; --line:#313244; --control:#6c7086;
|
|
26
|
+
--fg:#cdd6f4; --muted:#a6adc8; --accent:#89b4fa; --on-accent:#11111b; --accent-ink:#89b4fa;
|
|
27
|
+
--ok:#a6e3a1; --ok-ink:#a6e3a1; --warn:#f9e2af; --warn-ink:#f9e2af; --bad:#f38ba8; --bad-ink:#f38ba8;
|
|
28
|
+
color-scheme:dark}}
|
|
29
|
+
:root[data-theme="dark"]{
|
|
30
|
+
--page:#181825; --surface:#1e1e2e; --sunken:#11111b; --line:#313244; --control:#6c7086;
|
|
31
|
+
--fg:#cdd6f4; --muted:#a6adc8; --accent:#89b4fa; --on-accent:#11111b; --accent-ink:#89b4fa;
|
|
32
|
+
--ok:#a6e3a1; --ok-ink:#a6e3a1; --warn:#f9e2af; --warn-ink:#f9e2af; --bad:#f38ba8; --bad-ink:#f38ba8;
|
|
33
|
+
color-scheme:dark}
|
|
34
|
+
|
|
35
|
+
*{box-sizing:border-box}
|
|
36
|
+
html{background:var(--page)}
|
|
37
|
+
body{margin:0;background:var(--page);color:var(--fg);font:15px/1.55 var(--f-body);-webkit-font-smoothing:antialiased}
|
|
38
|
+
.wrap{max-width:var(--width);margin:0 auto;padding-left:max(16px,env(safe-area-inset-left,0px));padding-right:max(16px,env(safe-area-inset-right,0px));padding-block:32px 64px;display:grid;gap:24px}
|
|
39
|
+
.wrap>*{min-width:0}
|
|
40
|
+
h1,h2,h3{font-family:var(--f-display);margin:0;text-wrap:balance;letter-spacing:-.01em}
|
|
41
|
+
h1{font-size:clamp(28px,4vw,40px);line-height:1.05;font-weight:700}
|
|
42
|
+
h2{font-size:clamp(20px,2.4vw,24px);line-height:1.2;font-weight:700}
|
|
43
|
+
h3{font-size:17px;line-height:1.3;font-weight:600}
|
|
44
|
+
p{margin:0}
|
|
45
|
+
a{color:var(--accent-ink);text-underline-offset:3px}
|
|
46
|
+
code,kbd,pre{font-family:var(--f-mono);font-size:.86em}
|
|
47
|
+
pre{margin:0;padding:14px 16px;background:var(--sunken);border-radius:8px;overflow-x:auto;line-height:1.5}
|
|
48
|
+
:focus-visible{outline:2px solid var(--accent);outline-offset:2px}
|
|
49
|
+
|
|
50
|
+
.eyebrow,.label{font:600 12px/1.35 var(--f-body);color:var(--muted)}
|
|
51
|
+
header{display:grid;gap:8px}
|
|
52
|
+
.lede{color:var(--muted);max-width:68ch;font-size:16px}
|
|
53
|
+
.prose{display:grid;gap:12px;max-width:68ch}
|
|
54
|
+
section{display:grid;gap:14px}
|
|
55
|
+
|
|
56
|
+
.strip{display:flex;flex-wrap:wrap;gap:1px;background:var(--line);border:1px solid var(--line);border-radius:var(--radius);overflow:hidden}
|
|
57
|
+
.stat{flex:1 1 150px;display:grid;gap:2px;padding:14px 16px;background:var(--surface)}
|
|
58
|
+
.stat b{font:700 26px/1.1 var(--f-display);font-variant-numeric:tabular-nums}
|
|
59
|
+
.stat span{font-size:13px;color:var(--muted)}
|
|
60
|
+
|
|
61
|
+
.pill{display:inline-flex;align-items:center;gap:6px;font:600 11.5px/1.25 var(--f-body);padding:3px 8px;border-radius:5px;background:var(--neutral-soft);color:var(--muted)}
|
|
62
|
+
.pills{display:flex;flex-wrap:wrap;gap:5px}
|
|
63
|
+
.pill.accent{background:var(--accent-soft);color:var(--accent-ink)}
|
|
64
|
+
.pill.ok{background:var(--ok-soft);color:var(--ok-ink)}
|
|
65
|
+
.pill.warn{background:var(--warn-soft);color:var(--warn-ink)}
|
|
66
|
+
.pill.bad{background:var(--bad-soft);color:var(--bad-ink)}
|
|
67
|
+
|
|
68
|
+
.panel{background:var(--surface);border:1px solid var(--line);border-radius:var(--radius);padding:16px 18px;display:grid;gap:10px}
|
|
69
|
+
.note{border-left:3px solid var(--accent);padding:2px 0 2px 14px;display:grid;gap:4px;max-width:72ch}
|
|
70
|
+
.note.warn{border-color:var(--warn)}
|
|
71
|
+
|
|
72
|
+
.table{background:var(--surface);border:1px solid var(--line);border-radius:var(--radius);overflow-x:auto}
|
|
73
|
+
table{width:100%;border-collapse:collapse;font-size:14px}
|
|
74
|
+
th{font:600 12px/1.35 var(--f-body);color:var(--muted);text-align:left;padding:10px 14px;background:var(--sunken);border-bottom:1px solid var(--line);white-space:nowrap}
|
|
75
|
+
td{padding:11px 14px;border-bottom:1px solid var(--line);vertical-align:top;font-variant-numeric:tabular-nums}
|
|
76
|
+
tr:last-child td{border-bottom:0}
|
|
77
|
+
td.num,th.num{text-align:right;white-space:nowrap}
|
|
78
|
+
|
|
79
|
+
.rows{background:var(--surface);border:1px solid var(--line);border-radius:var(--radius);overflow:hidden}
|
|
80
|
+
.rows-head,.row>summary{display:grid;grid-template-columns:var(--cols,88px minmax(0,2fr) minmax(0,1fr) minmax(0,1.4fr));gap:16px;padding:12px 16px;align-items:start}
|
|
81
|
+
.rows-head{font:600 12px/1.35 var(--f-body);color:var(--muted);background:var(--sunken);border-bottom:1px solid var(--line)}
|
|
82
|
+
.row{border-bottom:1px solid var(--line)}
|
|
83
|
+
.row:last-child{border-bottom:0}
|
|
84
|
+
.row>summary{cursor:pointer;list-style:none}
|
|
85
|
+
.row>summary::-webkit-details-marker{display:none}
|
|
86
|
+
.row>summary>*{min-width:0}
|
|
87
|
+
.row>summary>:first-child::before{content:"▸";display:inline-block;margin-right:6px;color:var(--muted);font-size:11px;transition:transform .15s}
|
|
88
|
+
.row[open]>summary>:first-child::before{transform:rotate(90deg)}
|
|
89
|
+
.row-detail{padding:4px 16px 18px;display:grid;grid-template-columns:repeat(auto-fit,minmax(min(260px,100%),1fr));gap:14px 28px}
|
|
90
|
+
.row-detail dl{margin:0;display:grid;gap:10px;align-content:start}
|
|
91
|
+
.row-detail dd{margin:2px 0 0;font-size:13.5px;overflow-wrap:anywhere}
|
|
92
|
+
.row.closed>summary{color:var(--muted)}
|
|
93
|
+
|
|
94
|
+
.bar{display:flex;flex-wrap:wrap;gap:10px;align-items:center}
|
|
95
|
+
input,select,button{font:inherit;font-size:14px;color:var(--fg);background:var(--surface);border:1px solid var(--control);border-radius:8px;padding:8px 10px;min-width:0}
|
|
96
|
+
button{cursor:pointer}
|
|
97
|
+
button.primary{background:var(--accent);border-color:var(--accent);color:var(--on-accent);font-weight:600}
|
|
98
|
+
.chip{border:1px solid var(--line);border-radius:999px;padding:5px 11px;font-size:13px;font-weight:500}
|
|
99
|
+
.chip[aria-pressed="true"]{background:var(--accent-soft);border-color:var(--accent);color:var(--accent-ink)}
|
|
100
|
+
.count{margin-left:auto;font:13px var(--f-mono);color:var(--muted)}
|
|
101
|
+
|
|
102
|
+
footer{font-size:12.5px;color:var(--muted);display:grid;gap:4px;border-top:1px solid var(--line);padding-top:16px}
|
|
103
|
+
|
|
104
|
+
@media (max-width:720px){.rows-head{display:none}.row>summary{grid-template-columns:minmax(0,1fr);gap:6px}}
|
|
105
|
+
@media (hover:hover) and (pointer:fine){tbody tr:hover td,.row>summary:hover{background:var(--sunken)}button:hover{border-color:var(--accent)}}
|
|
106
|
+
@media (prefers-reduced-motion:reduce){*{transition:none!important;animation:none!important}}
|
|
107
|
+
</style>
|
|
108
|
+
</head>
|
|
109
|
+
<body>
|
|
110
|
+
<main class="wrap">
|
|
111
|
+
<header>
|
|
112
|
+
<div class="eyebrow">Specimen · artifacts-design</div>
|
|
113
|
+
<h1>Starter primitives</h1>
|
|
114
|
+
<p class="lede">Replace this body with the artifact's own composition. Keep the tokens and the primitives the page needs, and delete the rest.</p>
|
|
115
|
+
</header>
|
|
116
|
+
|
|
117
|
+
<section class="strip" aria-label="Summary">
|
|
118
|
+
<div class="stat"><b>34</b><span>Records</span></div>
|
|
119
|
+
<div class="stat"><b>23</b><span>Open</span></div>
|
|
120
|
+
<div class="stat"><b>4</b><span>Need attention</span></div>
|
|
121
|
+
</section>
|
|
122
|
+
|
|
123
|
+
<section>
|
|
124
|
+
<h2>Status and data</h2>
|
|
125
|
+
<div class="bar">
|
|
126
|
+
<input id="q" type="search" placeholder="Search" aria-label="Search">
|
|
127
|
+
<button class="chip" aria-pressed="true">All</button>
|
|
128
|
+
<button class="chip" aria-pressed="false">Open</button>
|
|
129
|
+
<span class="count">3 of 34</span>
|
|
130
|
+
</div>
|
|
131
|
+
<div class="table">
|
|
132
|
+
<table>
|
|
133
|
+
<thead><tr><th>Item</th><th>State</th><th class="num">Value</th></tr></thead>
|
|
134
|
+
<tbody>
|
|
135
|
+
<tr><td>Accent</td><td><span class="pill accent">In review</span></td><td class="num">1,204</td></tr>
|
|
136
|
+
<tr><td>Success</td><td><span class="pill ok">Passed</span></td><td class="num">98.6 %</td></tr>
|
|
137
|
+
<tr><td>Warning and error</td><td><span class="pill warn">Pending</span> <span class="pill bad">Failed</span></td><td class="num">−12</td></tr>
|
|
138
|
+
</tbody>
|
|
139
|
+
</table>
|
|
140
|
+
</div>
|
|
141
|
+
</section>
|
|
142
|
+
|
|
143
|
+
<section>
|
|
144
|
+
<h2>Expandable records</h2>
|
|
145
|
+
<div class="rows">
|
|
146
|
+
<div class="rows-head" aria-hidden="true"><span>ID</span><span>Title</span><span>Group</span><span>State</span></div>
|
|
147
|
+
<details class="row">
|
|
148
|
+
<summary><b>#2088</b><span>Parallelize search and listing data fetching</span><span>Performance</span><span class="pills"><span class="pill">Draft</span><span class="pill ok">Build passed</span></span></summary>
|
|
149
|
+
<div class="row-detail">
|
|
150
|
+
<dl><dt class="label">Next step</dt><dd>Keep separate and wait for team review.</dd></dl>
|
|
151
|
+
<dl><dt class="label">Branch</dt><dd><code>refactor/search-plp-parallel-fetch</code></dd></dl>
|
|
152
|
+
</div>
|
|
153
|
+
</details>
|
|
154
|
+
<details class="row closed">
|
|
155
|
+
<summary><b>#2086</b><span>Temporary workspace configuration</span><span>Temporary</span><span class="pills"><span class="pill">Closed</span></span></summary>
|
|
156
|
+
<div class="row-detail"><dl><dt class="label">Reason</dt><dd>Closed without merge by the owner.</dd></dl></div>
|
|
157
|
+
</details>
|
|
158
|
+
</div>
|
|
159
|
+
</section>
|
|
160
|
+
|
|
161
|
+
<section class="prose">
|
|
162
|
+
<h2>Reading text</h2>
|
|
163
|
+
<p>Body copy stays near 68 characters per line. Use <code>code</code> for identifiers and the <span class="label">label</span> style for metadata.</p>
|
|
164
|
+
<div class="note"><b>Note.</b><p>A note marks one consequential statement. It is not a container for ordinary paragraphs.</p></div>
|
|
165
|
+
</section>
|
|
166
|
+
|
|
167
|
+
<footer><span>Source and date of the data go here.</span></footer>
|
|
168
|
+
</main>
|
|
169
|
+
</body>
|
|
170
|
+
</html>
|
package/src/auth.d.ts
CHANGED
|
@@ -4,7 +4,10 @@ export declare function login(options: {
|
|
|
4
4
|
stateDir: string;
|
|
5
5
|
noBrowser: boolean;
|
|
6
6
|
onAuthorizationUrl: (url: string) => void;
|
|
7
|
-
}): Promise<
|
|
7
|
+
}): Promise<{
|
|
8
|
+
resource: string;
|
|
9
|
+
identity: Identity;
|
|
10
|
+
}>;
|
|
8
11
|
export declare function accessToken(options: {
|
|
9
12
|
resource: string;
|
|
10
13
|
stateDir: string;
|
package/src/auth.js
CHANGED
|
@@ -2,13 +2,12 @@ import { spawn } from 'node:child_process';
|
|
|
2
2
|
import { randomUUID } from 'node:crypto';
|
|
3
3
|
import { createServer } from 'node:http';
|
|
4
4
|
import * as oidc from 'openid-client';
|
|
5
|
-
import { canonicalResource, identitySchema, protectedResourceMetadataUrl, restBase } from '@yargote/artifacts-contracts/http';
|
|
6
|
-
import {
|
|
5
|
+
import { canonicalResource, httpErrorSchema, identitySchema, protectedResourceMetadataSchema, protectedResourceMetadataUrl, restBase } from '@yargote/artifacts-contracts/http';
|
|
6
|
+
import { HttpError } from '@yargote/artifacts-client';
|
|
7
7
|
import { CredentialStore } from "./credentials.js";
|
|
8
8
|
const networkTimeout = 10_000;
|
|
9
9
|
const callbackTimeout = 180_000;
|
|
10
10
|
const scopes = 'openid profile offline_access artifacts:read artifacts:write artifacts:publish';
|
|
11
|
-
const resourceMetadata = z.object({ resource: z.string(), authorization_servers: z.array(z.string()).min(1) });
|
|
12
11
|
function endpoint(value, issuer) {
|
|
13
12
|
const url = new URL(value);
|
|
14
13
|
const loopback = /^http:\/\/(?:127\.0\.0\.1|\[::1\]|localhost)(?::[0-9]+)?(?:\/|$)/.test(value);
|
|
@@ -18,12 +17,34 @@ function endpoint(value, issuer) {
|
|
|
18
17
|
throw new Error('OAuth endpoints must use the issuer origin');
|
|
19
18
|
return url;
|
|
20
19
|
}
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
20
|
+
class AuthTransportError extends Error {
|
|
21
|
+
}
|
|
22
|
+
function safeUrl(value) {
|
|
23
|
+
try {
|
|
24
|
+
const url = new URL(value);
|
|
25
|
+
return `${url.origin}${url.pathname}`;
|
|
26
|
+
}
|
|
27
|
+
catch {
|
|
28
|
+
return '[invalid endpoint]';
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
function authFailure(context, code, explanation, status) {
|
|
32
|
+
const message = `${context.phase} ${context.method} ${safeUrl(context.url)}${status === undefined ? '' : ` HTTP ${status}`}: ${explanation}`;
|
|
33
|
+
return status === undefined ? new AuthTransportError(message) : new HttpError(status, code, message);
|
|
34
|
+
}
|
|
35
|
+
async function boundedFetch(context, options = {}) {
|
|
36
|
+
const timeout = AbortSignal.timeout(networkTimeout);
|
|
37
|
+
const signal = options.signal ? AbortSignal.any([options.signal, timeout]) : timeout;
|
|
38
|
+
let response;
|
|
39
|
+
try {
|
|
40
|
+
response = await fetch(context.url, { ...options, redirect: 'manual', signal });
|
|
41
|
+
}
|
|
42
|
+
catch {
|
|
43
|
+
throw authFailure(context, 'network_error', timeout.aborted || (options.signal?.aborted && options.signal.reason instanceof DOMException && options.signal.reason.name === 'TimeoutError') ? 'Request timed out' : options.signal?.aborted ? 'Request cancelled' : 'Network request failed');
|
|
44
|
+
}
|
|
24
45
|
if (response.status >= 300 && response.status < 400) {
|
|
25
|
-
await response.body?.cancel();
|
|
26
|
-
throw
|
|
46
|
+
await response.body?.cancel().catch(() => { });
|
|
47
|
+
throw authFailure(context, 'redirect_refused', 'Redirect refused', response.status);
|
|
27
48
|
}
|
|
28
49
|
const reader = response.body?.getReader();
|
|
29
50
|
const chunks = [];
|
|
@@ -36,13 +57,13 @@ async function boundedFetch(url, options = {}) {
|
|
|
36
57
|
break;
|
|
37
58
|
size += chunk.value.byteLength;
|
|
38
59
|
if (size > 1024 * 1024)
|
|
39
|
-
throw new Error('
|
|
60
|
+
throw new Error('too large');
|
|
40
61
|
chunks.push(chunk.value);
|
|
41
62
|
}
|
|
42
63
|
}
|
|
43
|
-
catch
|
|
64
|
+
catch {
|
|
44
65
|
await reader.cancel().catch(() => { });
|
|
45
|
-
throw
|
|
66
|
+
throw authFailure(context, 'invalid_response', timeout.aborted || (options.signal?.aborted && options.signal.reason instanceof DOMException && options.signal.reason.name === 'TimeoutError') ? 'Response timed out' : options.signal?.aborted ? 'Request cancelled' : 'Cannot read response', response.status);
|
|
46
67
|
}
|
|
47
68
|
finally {
|
|
48
69
|
reader.releaseLock();
|
|
@@ -50,31 +71,155 @@ async function boundedFetch(url, options = {}) {
|
|
|
50
71
|
}
|
|
51
72
|
return new Response(size ? Buffer.concat(chunks) : null, { status: response.status, statusText: response.statusText, headers: response.headers });
|
|
52
73
|
}
|
|
53
|
-
function
|
|
74
|
+
function jsonResponse(response, context) {
|
|
75
|
+
if (response.headers.get('content-type')?.split(';')[0]?.trim().toLowerCase() !== 'application/json')
|
|
76
|
+
throw authFailure(context, 'invalid_response', 'Expected a JSON response', response.status);
|
|
77
|
+
return response.json().catch(() => { throw authFailure(context, 'invalid_response', 'Invalid JSON response', response.status); });
|
|
78
|
+
}
|
|
79
|
+
async function discoverResource(resource, terminal = false) {
|
|
80
|
+
const context = { phase: 'resource_metadata', method: 'GET', url: protectedResourceMetadataUrl(resource) };
|
|
81
|
+
const response = await boundedFetch(context);
|
|
82
|
+
if (!response.ok)
|
|
83
|
+
throw authFailure(context, response.status >= 500 ? 'service_error' : 'incompatible_resource', response.status >= 500 ? 'Resource metadata service failed' : 'Cannot discover the protected resource. Confirm the configured REST URL', response.status);
|
|
84
|
+
const document = await jsonResponse(response, context);
|
|
85
|
+
const parsed = protectedResourceMetadataSchema.safeParse(document);
|
|
86
|
+
if (!parsed.success)
|
|
87
|
+
throw authFailure(context, 'invalid_response', 'Invalid protected resource metadata', response.status);
|
|
88
|
+
if (parsed.data.resource !== resource)
|
|
89
|
+
throw authFailure(context, 'invalid_response', 'Protected resource metadata does not match the exact server URL', response.status);
|
|
90
|
+
if (terminal && parsed.data.artifacts_rest_resource !== undefined && parsed.data.artifacts_rest_resource !== resource)
|
|
91
|
+
throw authFailure(context, 'invalid_response', 'REST resource metadata must not advertise another artifacts_rest_resource', response.status);
|
|
92
|
+
const issuer = parsed.data.authorization_servers[0];
|
|
93
|
+
try {
|
|
94
|
+
endpoint(issuer);
|
|
95
|
+
}
|
|
96
|
+
catch {
|
|
97
|
+
throw authFailure(context, 'invalid_response', 'Invalid authorization server URL in protected resource metadata', response.status);
|
|
98
|
+
}
|
|
99
|
+
return { issuer, ...(parsed.data.artifacts_rest_resource === undefined ? {} : { restResource: parsed.data.artifacts_rest_resource }) };
|
|
100
|
+
}
|
|
101
|
+
function compatibleChallenge(value) {
|
|
102
|
+
if (!value)
|
|
103
|
+
return false;
|
|
104
|
+
const match = /^Bearer\s+(.+)$/i.exec(value);
|
|
105
|
+
if (!match)
|
|
106
|
+
return false;
|
|
107
|
+
const parameters = new Map();
|
|
108
|
+
const input = match[1];
|
|
109
|
+
const parameter = /\s*([!#$%&'*+.^_`|~0-9A-Za-z-]+)\s*=\s*(?:"((?:[^"\\]|\\[\x20-\x7e])*)"|([!#$%&'*+.^_`|~0-9A-Za-z-]+))\s*(,|$)/gy;
|
|
110
|
+
let position = 0;
|
|
111
|
+
while (position < input.length) {
|
|
112
|
+
parameter.lastIndex = position;
|
|
113
|
+
const param = parameter.exec(input);
|
|
114
|
+
if (!param || (param[4] === ',' && parameter.lastIndex === input.length))
|
|
115
|
+
return false;
|
|
116
|
+
const key = param[1].toLowerCase();
|
|
117
|
+
if (parameters.has(key))
|
|
118
|
+
return false;
|
|
119
|
+
parameters.set(key, param[2] === undefined ? param[3] : param[2].replace(/\\([\x20-\x7e])/g, '$1'));
|
|
120
|
+
position = parameter.lastIndex;
|
|
121
|
+
}
|
|
122
|
+
return parameters.get('error') === 'invalid_token' && (parameters.get('scope')?.split(/\s+/).includes('artifacts:read') ?? false);
|
|
123
|
+
}
|
|
124
|
+
async function checkIdentity(resource, request) {
|
|
125
|
+
const context = { phase: request.kind === 'anonymous' ? 'rest_preflight' : 'authenticated_identity', method: 'GET', url: `${restBase(resource)}/identity` };
|
|
126
|
+
const response = await boundedFetch(context, request.kind === 'anonymous' ? {} : { signal: request.signal, headers: { authorization: `Bearer ${request.accessToken}` } });
|
|
127
|
+
if (request.kind === 'anonymous') {
|
|
128
|
+
if (response.status === 401) {
|
|
129
|
+
const body = httpErrorSchema.safeParse(await jsonResponse(response, context));
|
|
130
|
+
if (body.success && body.data.error.code === 'unauthenticated' && compatibleChallenge(response.headers.get('www-authenticate')))
|
|
131
|
+
return;
|
|
132
|
+
}
|
|
133
|
+
throw authFailure(context, response.status >= 500 ? 'service_error' : 'incompatible_resource', response.status >= 500 ? 'REST identity service failed' : 'REST identity route is incompatible. Use the exact REST URL or configure artifacts_rest_resource on the MCP server', response.status);
|
|
134
|
+
}
|
|
135
|
+
if (!response.ok)
|
|
136
|
+
throw authFailure(context, response.status >= 500 ? 'service_error' : response.status === 401 || response.status === 403 ? 'access_denied' : 'incompatible_resource', response.status >= 500 ? 'REST identity service failed' : response.status === 401 || response.status === 403 ? 'OAuth grant cannot access this Artifacts server' : 'REST identity route is unavailable. Confirm the configured REST URL', response.status);
|
|
137
|
+
const parsed = identitySchema.safeParse(await jsonResponse(response, context));
|
|
138
|
+
if (!parsed.success)
|
|
139
|
+
throw authFailure(context, 'invalid_response', 'Invalid REST identity response', response.status);
|
|
140
|
+
if (request.claims.sub !== parsed.data.userId || (request.claims.sid !== undefined && request.claims.sid !== parsed.data.sessionId))
|
|
141
|
+
throw authFailure(context, 'invalid_response', 'OAuth identity does not match the Artifacts session', response.status);
|
|
142
|
+
return parsed.data;
|
|
143
|
+
}
|
|
144
|
+
async function oauth(issuer, signal, operation) {
|
|
145
|
+
const observations = [];
|
|
146
|
+
try {
|
|
147
|
+
const result = await operation(discoveryOptions(issuer, signal, observations));
|
|
148
|
+
if (result instanceof oidc.Configuration) {
|
|
149
|
+
validateConfiguration(result, issuer, observations);
|
|
150
|
+
result[oidc.customFetch] = discoveryOptions(issuer, signal)[oidc.customFetch];
|
|
151
|
+
}
|
|
152
|
+
return result;
|
|
153
|
+
}
|
|
154
|
+
catch (error) {
|
|
155
|
+
let cause = error;
|
|
156
|
+
let observed;
|
|
157
|
+
for (let depth = 0; depth < 5; depth++) {
|
|
158
|
+
if (cause instanceof HttpError || cause instanceof AuthTransportError)
|
|
159
|
+
throw cause;
|
|
160
|
+
const response = cause instanceof Response ? cause : cause instanceof Error && 'response' in cause ? cause.response : undefined;
|
|
161
|
+
if (response instanceof Response)
|
|
162
|
+
observed = observations.find((item) => item.response === response);
|
|
163
|
+
if (observed || !(cause instanceof Error))
|
|
164
|
+
break;
|
|
165
|
+
cause = cause.cause;
|
|
166
|
+
}
|
|
167
|
+
observed ??= observations.at(-1);
|
|
168
|
+
if (observed)
|
|
169
|
+
throw authFailure(observed.context, 'invalid_response', 'OAuth protocol validation failed', observed.response.status);
|
|
170
|
+
throw new Error('OAuth protocol validation failed');
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
function discoveryOptions(issuer, signal, observations) {
|
|
54
174
|
endpoint(issuer);
|
|
55
175
|
return {
|
|
56
176
|
timeout: networkTimeout / 1000,
|
|
57
177
|
execute: [...(new URL(issuer).protocol === 'http:' ? [oidc.allowInsecureRequests] : []), oidc.enableNonRepudiationChecks],
|
|
58
|
-
[oidc.customFetch]: (url, options) =>
|
|
178
|
+
[oidc.customFetch]: async (url, options) => {
|
|
179
|
+
const context = { phase: 'oauth', method: options.method ?? 'GET', url };
|
|
180
|
+
try {
|
|
181
|
+
endpoint(url, issuer);
|
|
182
|
+
}
|
|
183
|
+
catch {
|
|
184
|
+
throw authFailure({ ...context, url: issuer }, 'invalid_response', 'Invalid OAuth endpoint');
|
|
185
|
+
}
|
|
186
|
+
const response = await boundedFetch(context, { ...options, signal: signal && options.signal ? AbortSignal.any([signal, options.signal]) : signal ?? options.signal, body: options.body instanceof Uint8Array ? Uint8Array.from(options.body) : options.body });
|
|
187
|
+
if (!response.ok)
|
|
188
|
+
throw authFailure(context, response.status >= 500 ? 'service_error' : 'oauth_error', response.status >= 500 ? 'OAuth service failed' : 'OAuth request failed', response.status);
|
|
189
|
+
observations?.push({ context, response });
|
|
190
|
+
return response;
|
|
191
|
+
},
|
|
59
192
|
};
|
|
60
193
|
}
|
|
61
|
-
function validateConfiguration(config, issuer) {
|
|
194
|
+
function validateConfiguration(config, issuer, observations) {
|
|
195
|
+
const discovery = observations.find((item) => item.context.method === 'GET');
|
|
196
|
+
const registration = observations.find((item) => item.context.method === 'POST');
|
|
197
|
+
if (!discovery)
|
|
198
|
+
throw new Error('OAuth discovery response was not observed');
|
|
199
|
+
const failDiscovery = (message) => authFailure(discovery.context, 'invalid_response', message, discovery.response.status);
|
|
62
200
|
const metadata = config.serverMetadata();
|
|
63
201
|
if (metadata.issuer !== issuer)
|
|
64
|
-
throw
|
|
202
|
+
throw failDiscovery('OAuth issuer metadata does not match the configured issuer');
|
|
65
203
|
for (const [key, value] of Object.entries(metadata)) {
|
|
66
|
-
if ((key.endsWith('_endpoint') || key === 'jwks_uri') && typeof value === 'string')
|
|
67
|
-
|
|
204
|
+
if ((key.endsWith('_endpoint') || key === 'jwks_uri') && typeof value === 'string') {
|
|
205
|
+
try {
|
|
206
|
+
endpoint(value, issuer);
|
|
207
|
+
}
|
|
208
|
+
catch (error) {
|
|
209
|
+
const message = error instanceof Error && error.message === 'OAuth endpoints must use the issuer origin' ? error.message : 'OAuth URLs require HTTPS or an exact loopback HTTP host, without credentials, query, or fragment';
|
|
210
|
+
throw failDiscovery(message);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
68
213
|
}
|
|
69
214
|
if (!metadata.authorization_endpoint || !metadata.token_endpoint)
|
|
70
|
-
throw
|
|
71
|
-
if (config.clientMetadata().client_secret || config.clientMetadata().token_endpoint_auth_method !== 'none')
|
|
72
|
-
|
|
215
|
+
throw failDiscovery('OAuth metadata is missing authorization or token endpoints');
|
|
216
|
+
if (config.clientMetadata().client_secret || config.clientMetadata().token_endpoint_auth_method !== 'none') {
|
|
217
|
+
const message = 'The CLI requires a public OAuth client without a secret';
|
|
218
|
+
throw registration ? authFailure(registration.context, 'invalid_response', message, registration.response.status) : new Error(message);
|
|
219
|
+
}
|
|
73
220
|
}
|
|
74
221
|
async function configuration(registration, signal) {
|
|
75
|
-
|
|
76
|
-
validateConfiguration(config, registration.issuer);
|
|
77
|
-
return config;
|
|
222
|
+
return oauth(registration.issuer, signal, (options) => oidc.discovery(new URL(registration.issuer), registration.clientId, { token_endpoint_auth_method: 'none', id_token_signed_response_alg: 'EdDSA' }, oidc.None(), options));
|
|
78
223
|
}
|
|
79
224
|
function tokenRecord(tokens, previousRefresh) {
|
|
80
225
|
if (typeof tokens.expires_in !== 'number' || !Number.isFinite(tokens.expires_in) || tokens.expires_in <= 0)
|
|
@@ -142,7 +287,11 @@ async function openBrowser(url) {
|
|
|
142
287
|
});
|
|
143
288
|
}
|
|
144
289
|
export async function login(options) {
|
|
145
|
-
const
|
|
290
|
+
const source = canonicalResource(options.resource);
|
|
291
|
+
const metadata = await discoverResource(source);
|
|
292
|
+
const resource = metadata.restResource ?? source;
|
|
293
|
+
const { issuer } = resource === source ? metadata : await discoverResource(resource, true);
|
|
294
|
+
await checkIdentity(resource, { kind: 'anonymous' });
|
|
146
295
|
const store = await CredentialStore.open(options.stateDir);
|
|
147
296
|
let listener;
|
|
148
297
|
try {
|
|
@@ -151,14 +300,6 @@ export async function login(options) {
|
|
|
151
300
|
store.write(resource, { ...profile, epoch: profile.epoch + 1 });
|
|
152
301
|
return profile.epoch + 1;
|
|
153
302
|
});
|
|
154
|
-
const response = await boundedFetch(protectedResourceMetadataUrl(resource));
|
|
155
|
-
if (!response.ok)
|
|
156
|
-
throw new Error('Cannot discover the protected resource');
|
|
157
|
-
const metadata = resourceMetadata.parse(await response.json());
|
|
158
|
-
if (metadata.resource !== resource)
|
|
159
|
-
throw new Error('Protected resource metadata does not match the exact server URL');
|
|
160
|
-
const issuer = metadata.authorization_servers[0];
|
|
161
|
-
endpoint(issuer);
|
|
162
303
|
listener = await callback();
|
|
163
304
|
const { redirectUri, signal } = listener;
|
|
164
305
|
const config = await store.exclusive(async () => {
|
|
@@ -167,11 +308,10 @@ export async function login(options) {
|
|
|
167
308
|
throw new Error('Login was superseded by another login or logout');
|
|
168
309
|
if (profile.registration?.issuer === issuer)
|
|
169
310
|
return configuration(profile.registration, signal);
|
|
170
|
-
const registered = await oidc.dynamicClientRegistration(new URL(issuer), {
|
|
311
|
+
const registered = await oauth(issuer, signal, (options) => oidc.dynamicClientRegistration(new URL(issuer), {
|
|
171
312
|
client_name: 'Artifacts CLI', application_type: 'native', token_endpoint_auth_method: 'none', id_token_signed_response_alg: 'EdDSA',
|
|
172
313
|
redirect_uris: [redirectUri], grant_types: ['authorization_code', 'refresh_token'], response_types: ['code'], scope: scopes,
|
|
173
|
-
}, oidc.None(),
|
|
174
|
-
validateConfiguration(registered, issuer);
|
|
314
|
+
}, oidc.None(), options));
|
|
175
315
|
store.write(resource, { ...profile, registration: { issuer, clientId: registered.clientMetadata().client_id }, tokens: null, refreshAttempt: null });
|
|
176
316
|
return registered;
|
|
177
317
|
});
|
|
@@ -187,22 +327,21 @@ export async function login(options) {
|
|
|
187
327
|
if (!options.noBrowser)
|
|
188
328
|
await openBrowser(authorizationUrl);
|
|
189
329
|
const currentUrl = await authorization;
|
|
330
|
+
if (currentUrl.searchParams.has('error'))
|
|
331
|
+
throw new Error(currentUrl.searchParams.get('error') === 'access_denied' ? 'Authorization denied' : 'Authorization failed');
|
|
190
332
|
return await store.exclusive(async () => {
|
|
191
333
|
const profile = store.read(resource);
|
|
192
334
|
if (profile.epoch !== epoch)
|
|
193
335
|
throw new Error('Login was superseded by another login or logout');
|
|
194
|
-
const tokens = await
|
|
336
|
+
const tokens = await oauth(issuer, signal, (options) => {
|
|
337
|
+
config[oidc.customFetch] = options[oidc.customFetch];
|
|
338
|
+
return oidc.authorizationCodeGrant(config, currentUrl, { expectedState: state, expectedNonce: nonce, pkceCodeVerifier: verifier, idTokenExpected: true }, { resource });
|
|
339
|
+
});
|
|
195
340
|
const credentials = tokenRecord(tokens);
|
|
196
|
-
const
|
|
197
|
-
if (!identityResponse.ok)
|
|
198
|
-
throw new Error('The OAuth grant cannot access this Artifacts server');
|
|
199
|
-
const identity = identitySchema.parse(await identityResponse.json());
|
|
200
|
-
const claims = tokens.claims();
|
|
201
|
-
if (claims.sub !== identity.userId || (claims.sid !== undefined && claims.sid !== identity.sessionId))
|
|
202
|
-
throw new Error('OAuth identity does not match the Artifacts session');
|
|
341
|
+
const identity = await checkIdentity(resource, { kind: 'authenticated', accessToken: credentials.accessToken, signal, claims: tokens.claims() });
|
|
203
342
|
signal.throwIfAborted();
|
|
204
|
-
store.
|
|
205
|
-
return identity;
|
|
343
|
+
store.commitLogin(resource, epoch, credentials);
|
|
344
|
+
return { resource, identity };
|
|
206
345
|
});
|
|
207
346
|
}
|
|
208
347
|
finally {
|
package/src/credentials.d.ts
CHANGED
|
@@ -32,6 +32,8 @@ export declare class CredentialStore {
|
|
|
32
32
|
exclusive<T>(work: () => T | Promise<T>): Promise<T>;
|
|
33
33
|
read(resource: string): CredentialProfile;
|
|
34
34
|
write(resource: string, profile: CredentialProfile): void;
|
|
35
|
+
readSelectedResource(): string | undefined;
|
|
36
|
+
commitLogin(resource: string, epoch: number, tokens: Tokens): void;
|
|
35
37
|
close(): void;
|
|
36
38
|
}
|
|
37
39
|
export {};
|
package/src/credentials.js
CHANGED
|
@@ -4,6 +4,7 @@ import { join } from 'node:path';
|
|
|
4
4
|
import { DatabaseSync } from 'node:sqlite';
|
|
5
5
|
import { setTimeout as delay } from 'node:timers/promises';
|
|
6
6
|
import { z } from 'zod';
|
|
7
|
+
import { canonicalResource } from '@yargote/artifacts-contracts/http';
|
|
7
8
|
const registrationSchema = z.strictObject({ issuer: z.string(), clientId: z.string().min(1) });
|
|
8
9
|
const tokensSchema = z.strictObject({ accessToken: z.string().min(1), refreshToken: z.string().min(1).optional(), expiresAt: z.number().finite() });
|
|
9
10
|
const profileSchema = z.strictObject({
|
|
@@ -50,6 +51,7 @@ export class CredentialStore {
|
|
|
50
51
|
await store.exclusive(() => {
|
|
51
52
|
data.exec('PRAGMA busy_timeout = 0; PRAGMA synchronous = FULL; PRAGMA secure_delete = ON;');
|
|
52
53
|
data.exec('CREATE TABLE IF NOT EXISTS profiles (resource TEXT PRIMARY KEY, profile TEXT NOT NULL) STRICT');
|
|
54
|
+
data.exec('CREATE TABLE IF NOT EXISTS selected_resource (id INTEGER PRIMARY KEY CHECK (id = 1), resource TEXT NOT NULL) STRICT');
|
|
53
55
|
});
|
|
54
56
|
return store;
|
|
55
57
|
}
|
|
@@ -90,5 +92,25 @@ export class CredentialStore {
|
|
|
90
92
|
write(resource, profile) {
|
|
91
93
|
this.data.prepare('INSERT INTO profiles(resource, profile) VALUES (?, ?) ON CONFLICT(resource) DO UPDATE SET profile = excluded.profile').run(resource, JSON.stringify(profileSchema.parse(profile)));
|
|
92
94
|
}
|
|
95
|
+
readSelectedResource() {
|
|
96
|
+
const row = this.data.prepare('SELECT resource FROM selected_resource WHERE id = 1').get();
|
|
97
|
+
return row ? canonicalResource(String(row.resource)) : undefined;
|
|
98
|
+
}
|
|
99
|
+
commitLogin(resource, epoch, tokens) {
|
|
100
|
+
canonicalResource(resource);
|
|
101
|
+
this.data.exec('BEGIN IMMEDIATE');
|
|
102
|
+
try {
|
|
103
|
+
const profile = this.read(resource);
|
|
104
|
+
if (profile.epoch !== epoch)
|
|
105
|
+
throw new Error('Login was superseded by another login or logout');
|
|
106
|
+
this.write(resource, { ...profile, tokens, refreshAttempt: null });
|
|
107
|
+
this.data.prepare('INSERT INTO selected_resource(id, resource) VALUES (1, ?) ON CONFLICT(id) DO UPDATE SET resource = excluded.resource').run(resource);
|
|
108
|
+
this.data.exec('COMMIT');
|
|
109
|
+
}
|
|
110
|
+
catch (error) {
|
|
111
|
+
this.data.exec('ROLLBACK');
|
|
112
|
+
throw error;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
93
115
|
close() { this.data.close(); this.lock.close(); }
|
|
94
116
|
}
|