@cortexkit/common-auth 0.13.0 → 0.14.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.
- package/dist/pi-slot/index.d.ts +3 -0
- package/dist/pi-slot/index.js +2 -0
- package/dist/pi-slot/lock.d.ts +4 -0
- package/dist/pi-slot/lock.js +179 -0
- package/dist/pi-slot/slot.d.ts +49 -0
- package/dist/pi-slot/slot.js +380 -0
- package/package.json +7 -1
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
import { rmdirSync, statSync } from 'node:fs';
|
|
2
|
+
import { mkdir, rmdir, stat, utimes } from 'node:fs/promises';
|
|
3
|
+
// Protocol source: proper-lockfile 4.1.2 lib/lockfile.js and lib/mtime-precision.js;
|
|
4
|
+
// line-level citations and the Pi lock options are recorded in docs/sources.md.
|
|
5
|
+
const STALE = 30_000;
|
|
6
|
+
const UPDATE = STALE / 2;
|
|
7
|
+
let precision;
|
|
8
|
+
const active = new Map();
|
|
9
|
+
process.once('exit', () => {
|
|
10
|
+
for (const [path, identity] of active) {
|
|
11
|
+
try {
|
|
12
|
+
const observed = statSync(path);
|
|
13
|
+
if (sameDirectory(observed, identity) &&
|
|
14
|
+
observed.mtime.getTime() === identity.mtime)
|
|
15
|
+
rmdirSync(path);
|
|
16
|
+
}
|
|
17
|
+
catch {
|
|
18
|
+
/* A compromised or already removed lock is not ours to clean up. */
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
});
|
|
22
|
+
function sameDirectory(observed, identity) {
|
|
23
|
+
return observed.dev === identity.dev && observed.ino === identity.ino;
|
|
24
|
+
}
|
|
25
|
+
function errorCode(error) {
|
|
26
|
+
return typeof error === 'object' && error !== null && 'code' in error
|
|
27
|
+
? error.code
|
|
28
|
+
: undefined;
|
|
29
|
+
}
|
|
30
|
+
function held() {
|
|
31
|
+
return Object.assign(new Error('Pi auth lock held'), { code: 'ELOCKED' });
|
|
32
|
+
}
|
|
33
|
+
async function remove(path) {
|
|
34
|
+
try {
|
|
35
|
+
await rmdir(path);
|
|
36
|
+
}
|
|
37
|
+
catch (error) {
|
|
38
|
+
if (errorCode(error) !== 'ENOENT')
|
|
39
|
+
throw error;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
async function acquire(path, stale) {
|
|
43
|
+
try {
|
|
44
|
+
await mkdir(path);
|
|
45
|
+
}
|
|
46
|
+
catch (error) {
|
|
47
|
+
if (errorCode(error) !== 'EEXIST')
|
|
48
|
+
throw error;
|
|
49
|
+
if (stale <= 0)
|
|
50
|
+
throw held();
|
|
51
|
+
let mtime;
|
|
52
|
+
try {
|
|
53
|
+
mtime = (await stat(path)).mtime.getTime();
|
|
54
|
+
}
|
|
55
|
+
catch (error) {
|
|
56
|
+
if (errorCode(error) === 'ENOENT')
|
|
57
|
+
return acquire(path, 0);
|
|
58
|
+
throw error;
|
|
59
|
+
}
|
|
60
|
+
if (!(mtime < Date.now() - stale))
|
|
61
|
+
throw held();
|
|
62
|
+
// Match upstream: rmdir (ignore ENOENT), then one mkdir attempt without another stale check.
|
|
63
|
+
await remove(path);
|
|
64
|
+
return acquire(path, 0);
|
|
65
|
+
}
|
|
66
|
+
try {
|
|
67
|
+
if (!precision) {
|
|
68
|
+
const probe = new Date(Math.ceil(Date.now() / 1_000) * 1_000 + 5);
|
|
69
|
+
await utimes(path, probe, probe);
|
|
70
|
+
}
|
|
71
|
+
const observed = await stat(path);
|
|
72
|
+
const mtime = observed.mtime.getTime();
|
|
73
|
+
precision ??= mtime % 1_000 === 0 ? 's' : 'ms';
|
|
74
|
+
return { dev: observed.dev, ino: observed.ino, mtime };
|
|
75
|
+
}
|
|
76
|
+
catch (error) {
|
|
77
|
+
await remove(path).catch(() => { });
|
|
78
|
+
throw error;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
/** The same mkdir/mtime/rmdir protocol as Pi's proper-lockfile, with realpath disabled. */
|
|
82
|
+
export async function acquirePiLock(authPath, onCompromised, onRenew) {
|
|
83
|
+
const path = `${authPath}.lock`;
|
|
84
|
+
const identity = await acquire(path, STALE);
|
|
85
|
+
let mtime = identity.mtime;
|
|
86
|
+
let lastUpdate = Date.now();
|
|
87
|
+
let released = false;
|
|
88
|
+
let timer;
|
|
89
|
+
active.set(path, identity);
|
|
90
|
+
function compromise() {
|
|
91
|
+
released = true;
|
|
92
|
+
if (timer)
|
|
93
|
+
clearTimeout(timer);
|
|
94
|
+
active.delete(path);
|
|
95
|
+
onCompromised();
|
|
96
|
+
}
|
|
97
|
+
function schedule(delay = UPDATE) {
|
|
98
|
+
if (released)
|
|
99
|
+
return;
|
|
100
|
+
timer = setTimeout(() => {
|
|
101
|
+
void update();
|
|
102
|
+
}, delay);
|
|
103
|
+
timer.unref();
|
|
104
|
+
}
|
|
105
|
+
function retry(error) {
|
|
106
|
+
if (released)
|
|
107
|
+
return;
|
|
108
|
+
if (errorCode(error) === 'ENOENT' || lastUpdate + STALE < Date.now())
|
|
109
|
+
compromise();
|
|
110
|
+
else
|
|
111
|
+
schedule(1_000);
|
|
112
|
+
}
|
|
113
|
+
async function update() {
|
|
114
|
+
if (released)
|
|
115
|
+
return;
|
|
116
|
+
let observed;
|
|
117
|
+
try {
|
|
118
|
+
observed = await stat(path);
|
|
119
|
+
}
|
|
120
|
+
catch (error) {
|
|
121
|
+
retry(error);
|
|
122
|
+
return;
|
|
123
|
+
}
|
|
124
|
+
if (released)
|
|
125
|
+
return;
|
|
126
|
+
if (!sameDirectory(observed, identity) ||
|
|
127
|
+
observed.mtime.getTime() !== mtime) {
|
|
128
|
+
compromise();
|
|
129
|
+
return;
|
|
130
|
+
}
|
|
131
|
+
const next = new Date(precision === 's' ? Math.ceil(Date.now() / 1_000) * 1_000 : Date.now());
|
|
132
|
+
try {
|
|
133
|
+
await utimes(path, next, next);
|
|
134
|
+
}
|
|
135
|
+
catch (error) {
|
|
136
|
+
retry(error);
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
if (released)
|
|
140
|
+
return;
|
|
141
|
+
mtime = next.getTime();
|
|
142
|
+
active.set(path, { ...identity, mtime });
|
|
143
|
+
lastUpdate = Date.now();
|
|
144
|
+
schedule();
|
|
145
|
+
}
|
|
146
|
+
// Tests can resume a paused renewal without waiting for the production timer.
|
|
147
|
+
onRenew?.(async () => {
|
|
148
|
+
if (timer)
|
|
149
|
+
clearTimeout(timer);
|
|
150
|
+
await update();
|
|
151
|
+
});
|
|
152
|
+
schedule();
|
|
153
|
+
return {
|
|
154
|
+
async release() {
|
|
155
|
+
if (released)
|
|
156
|
+
return;
|
|
157
|
+
released = true;
|
|
158
|
+
if (timer)
|
|
159
|
+
clearTimeout(timer);
|
|
160
|
+
active.delete(path);
|
|
161
|
+
let observed;
|
|
162
|
+
try {
|
|
163
|
+
observed = await stat(path);
|
|
164
|
+
}
|
|
165
|
+
catch (error) {
|
|
166
|
+
if (errorCode(error) !== 'ENOENT')
|
|
167
|
+
throw error;
|
|
168
|
+
compromise();
|
|
169
|
+
return;
|
|
170
|
+
}
|
|
171
|
+
if (!sameDirectory(observed, identity) ||
|
|
172
|
+
mtime !== observed.mtime.getTime()) {
|
|
173
|
+
compromise();
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
await remove(path);
|
|
177
|
+
},
|
|
178
|
+
};
|
|
179
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
export type PiSlotErrorCode = 'invalid-options' | 'invalid-auth' | 'invalid-stash' | 'unsafe-path' | 'missing-stash' | 'conflict' | 'lock-timeout' | 'lock-compromised' | 'io';
|
|
2
|
+
/** Errors deliberately contain neither paths nor credentials nor underlying error messages. */
|
|
3
|
+
export declare class PiSlotError extends Error {
|
|
4
|
+
readonly code: PiSlotErrorCode;
|
|
5
|
+
constructor(code: PiSlotErrorCode);
|
|
6
|
+
}
|
|
7
|
+
export interface PiSlotOptions {
|
|
8
|
+
authPath: string;
|
|
9
|
+
provider: string;
|
|
10
|
+
/**
|
|
11
|
+
* Where the provider's original Pi login is kept while the vault serves.
|
|
12
|
+
* Put it in a private directory, and give each provider its own file: one
|
|
13
|
+
* stash holds one provider's original login, and a second provider writing
|
|
14
|
+
* to it would overwrite the first one's backup.
|
|
15
|
+
*/
|
|
16
|
+
stashPath: string;
|
|
17
|
+
/**
|
|
18
|
+
* The api_key Pi stores in the slot while the vault serves. It is a fixed,
|
|
19
|
+
* non-secret string that no provider accepts. Pi runs a key starting with
|
|
20
|
+
* `!` as a shell command and expands `$NAME` from the environment, so the
|
|
21
|
+
* placeholder may contain neither.
|
|
22
|
+
*/
|
|
23
|
+
placeholderKey: string;
|
|
24
|
+
lockTimeoutMs?: number;
|
|
25
|
+
}
|
|
26
|
+
export interface PiSlotInspection {
|
|
27
|
+
slot: 'original' | 'placeholder' | 'foreign' | 'empty';
|
|
28
|
+
stash: 'valid' | 'missing';
|
|
29
|
+
}
|
|
30
|
+
export interface PiSlot {
|
|
31
|
+
inspect(): Promise<PiSlotInspection>;
|
|
32
|
+
enterVault(): Promise<void>;
|
|
33
|
+
exitVault(): Promise<'restored' | 'conflict' | 'nothing-to-do'>;
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* Production entry point. Pi caches which models are usable; after a
|
|
37
|
+
* successful transition the extension calls `ctx.modelRegistry.refresh()` so
|
|
38
|
+
* Pi re-reads the slot it just changed.
|
|
39
|
+
*/
|
|
40
|
+
export declare function openPiSlot(options: PiSlotOptions): PiSlot;
|
|
41
|
+
/**
|
|
42
|
+
* Internal test entry point: pause reads, renewals, or renames to simulate races,
|
|
43
|
+
* and observe durable writes/deletion to simulate crashes. Not a public export.
|
|
44
|
+
*/
|
|
45
|
+
export declare function createPiSlot(options: PiSlotOptions, onStep?: (step: 'stash-written' | 'auth-written' | 'stash-deleted') => void, hooks?: {
|
|
46
|
+
afterReadCheck?: (path: string) => Promise<void>;
|
|
47
|
+
onRenew?: (renew: () => Promise<void>) => void;
|
|
48
|
+
beforeRename?: (path: string) => Promise<void>;
|
|
49
|
+
}): PiSlot;
|
|
@@ -0,0 +1,380 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { constants } from 'node:fs';
|
|
3
|
+
import { lstat, mkdir, open, unlink } from 'node:fs/promises';
|
|
4
|
+
import { dirname, resolve } from 'node:path';
|
|
5
|
+
import { setTimeout as sleep } from 'node:timers/promises';
|
|
6
|
+
import { writeJsonAtomic } from '../fs/atomic-write.js';
|
|
7
|
+
import { acquirePiLock } from './lock.js';
|
|
8
|
+
/** Errors deliberately contain neither paths nor credentials nor underlying error messages. */
|
|
9
|
+
export class PiSlotError extends Error {
|
|
10
|
+
code;
|
|
11
|
+
constructor(code) {
|
|
12
|
+
super(`Pi slot: ${code}`);
|
|
13
|
+
this.code = code;
|
|
14
|
+
this.name = 'PiSlotError';
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
// JSON.parse validates grammar first. This scan only locates top-level value text ranges.
|
|
18
|
+
function rootSpans(text) {
|
|
19
|
+
let i = text.indexOf('{') + 1;
|
|
20
|
+
const root = { offset: i - 1, children: [] };
|
|
21
|
+
const whitespace = () => {
|
|
22
|
+
while (/\s/.test(text[i] ?? '') && i < text.length)
|
|
23
|
+
i++;
|
|
24
|
+
};
|
|
25
|
+
const stringEnd = () => {
|
|
26
|
+
i++;
|
|
27
|
+
while (i < text.length) {
|
|
28
|
+
if (text[i++] === '"')
|
|
29
|
+
return;
|
|
30
|
+
if (text[i - 1] === '\\')
|
|
31
|
+
i++;
|
|
32
|
+
}
|
|
33
|
+
};
|
|
34
|
+
whitespace();
|
|
35
|
+
while (text[i] !== '}') {
|
|
36
|
+
const start = i;
|
|
37
|
+
stringEnd();
|
|
38
|
+
const key = JSON.parse(text.slice(start, i));
|
|
39
|
+
whitespace();
|
|
40
|
+
i++; // colon
|
|
41
|
+
whitespace();
|
|
42
|
+
const offset = i;
|
|
43
|
+
let depth = 0;
|
|
44
|
+
while (i < text.length) {
|
|
45
|
+
const char = text[i];
|
|
46
|
+
if (char === '"') {
|
|
47
|
+
stringEnd();
|
|
48
|
+
continue;
|
|
49
|
+
}
|
|
50
|
+
if (char === '{' || char === '[')
|
|
51
|
+
depth++;
|
|
52
|
+
if (char === '}' || char === ']') {
|
|
53
|
+
if (depth === 0)
|
|
54
|
+
break;
|
|
55
|
+
depth--;
|
|
56
|
+
}
|
|
57
|
+
if (char === ',' && depth === 0)
|
|
58
|
+
break;
|
|
59
|
+
i++;
|
|
60
|
+
}
|
|
61
|
+
let end = i;
|
|
62
|
+
while (/\s/.test(text[end - 1] ?? ''))
|
|
63
|
+
end--;
|
|
64
|
+
root.children.push({
|
|
65
|
+
key,
|
|
66
|
+
offset: start,
|
|
67
|
+
length: end - start,
|
|
68
|
+
value: { offset, length: end - offset },
|
|
69
|
+
});
|
|
70
|
+
whitespace();
|
|
71
|
+
if (text[i] === '}')
|
|
72
|
+
break;
|
|
73
|
+
i++; // comma
|
|
74
|
+
whitespace();
|
|
75
|
+
}
|
|
76
|
+
return root;
|
|
77
|
+
}
|
|
78
|
+
function object(value) {
|
|
79
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
80
|
+
}
|
|
81
|
+
function canonical(value) {
|
|
82
|
+
if (Array.isArray(value))
|
|
83
|
+
return `[${value.map(canonical).join(',')}]`;
|
|
84
|
+
if (object(value)) {
|
|
85
|
+
return `{${Object.keys(value)
|
|
86
|
+
.sort()
|
|
87
|
+
.map((key) => `${JSON.stringify(key)}:${canonical(value[key])}`)
|
|
88
|
+
.join(',')}}`;
|
|
89
|
+
}
|
|
90
|
+
return JSON.stringify(value);
|
|
91
|
+
}
|
|
92
|
+
function digest(value) {
|
|
93
|
+
return createHash('sha256').update(canonical(value)).digest('hex');
|
|
94
|
+
}
|
|
95
|
+
function code(error) {
|
|
96
|
+
return object(error) ? error.code : undefined;
|
|
97
|
+
}
|
|
98
|
+
async function safeRead(path, privateFile = false, afterReadCheck) {
|
|
99
|
+
let file;
|
|
100
|
+
try {
|
|
101
|
+
file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW);
|
|
102
|
+
const stat = await file.stat();
|
|
103
|
+
if (!stat.isFile() || (privateFile && (stat.mode & 0o777) !== 0o600)) {
|
|
104
|
+
throw new PiSlotError('unsafe-path');
|
|
105
|
+
}
|
|
106
|
+
await afterReadCheck?.(path);
|
|
107
|
+
// Refuse a replaced pathname even though the descriptor still pins the checked file.
|
|
108
|
+
const current = await lstat(path);
|
|
109
|
+
if (!current.isFile() ||
|
|
110
|
+
current.dev !== stat.dev ||
|
|
111
|
+
current.ino !== stat.ino) {
|
|
112
|
+
throw new PiSlotError('unsafe-path');
|
|
113
|
+
}
|
|
114
|
+
const bytes = await file.readFile();
|
|
115
|
+
const text = bytes.toString('utf8');
|
|
116
|
+
if (!bytes.equals(Buffer.from(text))) {
|
|
117
|
+
throw new PiSlotError(privateFile ? 'invalid-stash' : 'invalid-auth');
|
|
118
|
+
}
|
|
119
|
+
return text;
|
|
120
|
+
}
|
|
121
|
+
catch (error) {
|
|
122
|
+
if (code(error) === 'ENOENT' && !file)
|
|
123
|
+
return undefined;
|
|
124
|
+
if (code(error) === 'ELOOP' || code(error) === 'ENOENT') {
|
|
125
|
+
throw new PiSlotError('unsafe-path');
|
|
126
|
+
}
|
|
127
|
+
throw error;
|
|
128
|
+
}
|
|
129
|
+
finally {
|
|
130
|
+
await file?.close();
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
function parseAuth(text, provider) {
|
|
134
|
+
try {
|
|
135
|
+
const data = JSON.parse(text);
|
|
136
|
+
if (!object(data))
|
|
137
|
+
throw new Error();
|
|
138
|
+
const root = rootSpans(text);
|
|
139
|
+
const properties = root.children;
|
|
140
|
+
// Duplicate provider keys have ambiguous byte ownership, even though JSON.parse accepts them.
|
|
141
|
+
const names = properties.map((node) => node.key);
|
|
142
|
+
if (new Set(names).size !== names.length)
|
|
143
|
+
throw new Error();
|
|
144
|
+
const property = properties.find((node) => node.key === provider);
|
|
145
|
+
const entry = property ? data[provider] : null;
|
|
146
|
+
if (entry !== null && !object(entry))
|
|
147
|
+
throw new Error();
|
|
148
|
+
if (property && entry === null)
|
|
149
|
+
throw new Error();
|
|
150
|
+
return { text, root, property, entry: entry };
|
|
151
|
+
}
|
|
152
|
+
catch {
|
|
153
|
+
throw new PiSlotError('invalid-auth');
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
function entryText(auth) {
|
|
157
|
+
const value = auth.property?.value;
|
|
158
|
+
return value
|
|
159
|
+
? auth.text.slice(value.offset, value.offset + value.length)
|
|
160
|
+
: null;
|
|
161
|
+
}
|
|
162
|
+
function replaceEntry(auth, provider, next) {
|
|
163
|
+
const { text, root, property } = auth;
|
|
164
|
+
const properties = root.children ?? [];
|
|
165
|
+
if (property) {
|
|
166
|
+
const value = property.value;
|
|
167
|
+
if (!value)
|
|
168
|
+
throw new PiSlotError('invalid-auth');
|
|
169
|
+
if (next !== null) {
|
|
170
|
+
return (text.slice(0, value.offset) +
|
|
171
|
+
next +
|
|
172
|
+
text.slice(value.offset + value.length));
|
|
173
|
+
}
|
|
174
|
+
const index = properties.indexOf(property);
|
|
175
|
+
const previous = properties[index - 1];
|
|
176
|
+
const following = properties[index + 1];
|
|
177
|
+
const start = previous ? previous.offset + previous.length : property.offset;
|
|
178
|
+
const end = !previous && following
|
|
179
|
+
? following.offset
|
|
180
|
+
: property.offset + property.length;
|
|
181
|
+
return text.slice(0, start) + text.slice(end);
|
|
182
|
+
}
|
|
183
|
+
if (next === null)
|
|
184
|
+
return text;
|
|
185
|
+
const last = properties.at(-1);
|
|
186
|
+
// Insert next to the last value, not after its whitespace, so deletion reverses an empty-slot swap.
|
|
187
|
+
const offset = last ? last.offset + last.length : root.offset + 1;
|
|
188
|
+
return `${text.slice(0, offset)}${last ? ',' : ''}${JSON.stringify(provider)}:${next}${text.slice(offset)}`;
|
|
189
|
+
}
|
|
190
|
+
async function syncDir(path) {
|
|
191
|
+
const dir = await open(path, 'r');
|
|
192
|
+
try {
|
|
193
|
+
await dir.sync();
|
|
194
|
+
}
|
|
195
|
+
finally {
|
|
196
|
+
await dir.close();
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
async function atomicWrite(path, text, assertLock, beforeRename) {
|
|
200
|
+
await writeJsonAtomic(path, null, {
|
|
201
|
+
serialize: () => text,
|
|
202
|
+
durable: true,
|
|
203
|
+
beforeRename: async () => {
|
|
204
|
+
await beforeRename?.(path);
|
|
205
|
+
assertLock();
|
|
206
|
+
},
|
|
207
|
+
});
|
|
208
|
+
}
|
|
209
|
+
/**
|
|
210
|
+
* Production entry point. Pi caches which models are usable; after a
|
|
211
|
+
* successful transition the extension calls `ctx.modelRegistry.refresh()` so
|
|
212
|
+
* Pi re-reads the slot it just changed.
|
|
213
|
+
*/
|
|
214
|
+
export function openPiSlot(options) {
|
|
215
|
+
return createPiSlot(options);
|
|
216
|
+
}
|
|
217
|
+
/**
|
|
218
|
+
* Internal test entry point: pause reads, renewals, or renames to simulate races,
|
|
219
|
+
* and observe durable writes/deletion to simulate crashes. Not a public export.
|
|
220
|
+
*/
|
|
221
|
+
export function createPiSlot(options, onStep, hooks) {
|
|
222
|
+
const { provider, placeholderKey } = options;
|
|
223
|
+
const timeout = options.lockTimeoutMs ?? 30_000;
|
|
224
|
+
if (!provider ||
|
|
225
|
+
!options.authPath ||
|
|
226
|
+
!options.stashPath ||
|
|
227
|
+
!placeholderKey ||
|
|
228
|
+
placeholderKey.startsWith('!') ||
|
|
229
|
+
placeholderKey.includes('$') ||
|
|
230
|
+
!Number.isFinite(timeout) ||
|
|
231
|
+
timeout < 0) {
|
|
232
|
+
throw new PiSlotError('invalid-options');
|
|
233
|
+
}
|
|
234
|
+
const authPath = resolve(options.authPath);
|
|
235
|
+
const stashPath = resolve(options.stashPath);
|
|
236
|
+
if (authPath === stashPath || stashPath === `${authPath}.lock`) {
|
|
237
|
+
throw new PiSlotError('invalid-options');
|
|
238
|
+
}
|
|
239
|
+
const authIdentity = digest(authPath);
|
|
240
|
+
const placeholderIdentity = digest(placeholderKey);
|
|
241
|
+
const placeholder = { type: 'api_key', key: placeholderKey };
|
|
242
|
+
const isPlaceholder = (entry) => digest(entry) === digest(placeholder);
|
|
243
|
+
async function loadStash() {
|
|
244
|
+
const text = await safeRead(stashPath, true, hooks?.afterReadCheck);
|
|
245
|
+
if (text === undefined)
|
|
246
|
+
return undefined;
|
|
247
|
+
try {
|
|
248
|
+
const stash = JSON.parse(text);
|
|
249
|
+
if (stash.version !== 1 ||
|
|
250
|
+
stash.provider !== provider ||
|
|
251
|
+
stash.authIdentity !== authIdentity ||
|
|
252
|
+
stash.placeholderIdentity !== placeholderIdentity ||
|
|
253
|
+
(stash.entry !== null && !object(stash.entry)) ||
|
|
254
|
+
stash.sha256 !== digest(stash.entry) ||
|
|
255
|
+
(stash.entry === null
|
|
256
|
+
? stash.entryJson !== null
|
|
257
|
+
: typeof stash.entryJson !== 'string' ||
|
|
258
|
+
digest(JSON.parse(stash.entryJson)) !== stash.sha256)) {
|
|
259
|
+
throw new Error();
|
|
260
|
+
}
|
|
261
|
+
return stash;
|
|
262
|
+
}
|
|
263
|
+
catch {
|
|
264
|
+
throw new PiSlotError('invalid-stash');
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
async function locked(fn) {
|
|
268
|
+
let release;
|
|
269
|
+
let compromised = false;
|
|
270
|
+
const assertLock = () => {
|
|
271
|
+
if (compromised)
|
|
272
|
+
throw new PiSlotError('lock-compromised');
|
|
273
|
+
};
|
|
274
|
+
try {
|
|
275
|
+
await mkdir(dirname(authPath), { recursive: true, mode: 0o700 });
|
|
276
|
+
const deadline = Date.now() + timeout;
|
|
277
|
+
let retry = 0;
|
|
278
|
+
while (!release) {
|
|
279
|
+
try {
|
|
280
|
+
const lease = await acquirePiLock(authPath, () => {
|
|
281
|
+
compromised = true;
|
|
282
|
+
}, hooks?.onRenew);
|
|
283
|
+
release = lease.release;
|
|
284
|
+
}
|
|
285
|
+
catch (error) {
|
|
286
|
+
if (code(error) !== 'ELOCKED')
|
|
287
|
+
throw error;
|
|
288
|
+
const remaining = deadline - Date.now();
|
|
289
|
+
if (remaining <= 0)
|
|
290
|
+
throw new PiSlotError('lock-timeout');
|
|
291
|
+
await sleep(Math.min(Math.round(Math.min(10 * 2 ** retry++, 1_000) * (1 + Math.random())), remaining));
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
assertLock();
|
|
295
|
+
const result = await fn(assertLock);
|
|
296
|
+
assertLock();
|
|
297
|
+
return result;
|
|
298
|
+
}
|
|
299
|
+
catch (error) {
|
|
300
|
+
if (error instanceof PiSlotError)
|
|
301
|
+
throw error;
|
|
302
|
+
throw new PiSlotError('io');
|
|
303
|
+
}
|
|
304
|
+
finally {
|
|
305
|
+
await release?.().catch(() => { });
|
|
306
|
+
assertLock();
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
async function load() {
|
|
310
|
+
const auth = parseAuth((await safeRead(authPath, false, hooks?.afterReadCheck)) ?? '{}', provider);
|
|
311
|
+
const stash = await loadStash();
|
|
312
|
+
return { auth, stash };
|
|
313
|
+
}
|
|
314
|
+
async function deleteStash(assertLock) {
|
|
315
|
+
assertLock();
|
|
316
|
+
await unlink(stashPath);
|
|
317
|
+
await syncDir(dirname(stashPath));
|
|
318
|
+
onStep?.('stash-deleted');
|
|
319
|
+
}
|
|
320
|
+
return {
|
|
321
|
+
inspect: () => locked(async () => {
|
|
322
|
+
const { auth, stash } = await load();
|
|
323
|
+
const slot = isPlaceholder(auth.entry)
|
|
324
|
+
? 'placeholder'
|
|
325
|
+
: auth.entry === null
|
|
326
|
+
? 'empty'
|
|
327
|
+
: !stash || digest(auth.entry) === stash.sha256
|
|
328
|
+
? 'original'
|
|
329
|
+
: 'foreign';
|
|
330
|
+
return { slot, stash: stash ? 'valid' : 'missing' };
|
|
331
|
+
}),
|
|
332
|
+
enterVault: () => locked(async (assertLock) => {
|
|
333
|
+
const { auth, stash } = await load();
|
|
334
|
+
if (isPlaceholder(auth.entry)) {
|
|
335
|
+
if (!stash)
|
|
336
|
+
throw new PiSlotError('missing-stash');
|
|
337
|
+
return;
|
|
338
|
+
}
|
|
339
|
+
if (stash && digest(auth.entry) !== stash.sha256)
|
|
340
|
+
throw new PiSlotError('conflict');
|
|
341
|
+
if (!stash) {
|
|
342
|
+
await mkdir(dirname(stashPath), { recursive: true, mode: 0o700 });
|
|
343
|
+
const dir = await lstat(dirname(stashPath));
|
|
344
|
+
if (!dir.isDirectory() || (dir.mode & 0o777) !== 0o700)
|
|
345
|
+
throw new PiSlotError('unsafe-path');
|
|
346
|
+
const saved = {
|
|
347
|
+
version: 1,
|
|
348
|
+
provider,
|
|
349
|
+
authIdentity,
|
|
350
|
+
placeholderIdentity,
|
|
351
|
+
entry: auth.entry,
|
|
352
|
+
entryJson: entryText(auth),
|
|
353
|
+
sha256: digest(auth.entry),
|
|
354
|
+
};
|
|
355
|
+
await atomicWrite(stashPath, JSON.stringify(saved), assertLock, hooks?.beforeRename);
|
|
356
|
+
onStep?.('stash-written');
|
|
357
|
+
}
|
|
358
|
+
await atomicWrite(authPath, replaceEntry(auth, provider, JSON.stringify(placeholder)), assertLock, hooks?.beforeRename);
|
|
359
|
+
onStep?.('auth-written');
|
|
360
|
+
}),
|
|
361
|
+
exitVault: () => locked(async (assertLock) => {
|
|
362
|
+
const { auth, stash } = await load();
|
|
363
|
+
if (!stash) {
|
|
364
|
+
if (isPlaceholder(auth.entry))
|
|
365
|
+
throw new PiSlotError('missing-stash');
|
|
366
|
+
return 'nothing-to-do';
|
|
367
|
+
}
|
|
368
|
+
if (isPlaceholder(auth.entry)) {
|
|
369
|
+
await atomicWrite(authPath, replaceEntry(auth, provider, stash.entryJson), assertLock, hooks?.beforeRename);
|
|
370
|
+
onStep?.('auth-written');
|
|
371
|
+
}
|
|
372
|
+
else if (digest(auth.entry) !== stash.sha256) {
|
|
373
|
+
return 'conflict';
|
|
374
|
+
}
|
|
375
|
+
// Also completes a restore interrupted between the auth rename and stash deletion.
|
|
376
|
+
await deleteStash(assertLock);
|
|
377
|
+
return 'restored';
|
|
378
|
+
}),
|
|
379
|
+
};
|
|
380
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cortexkit/common-auth",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.14.0",
|
|
4
4
|
"description": "Shared code for the CortexKit auth plugins: account pool, quota and routing, commands and auth menu, OpenCode 2 hooks, Claustrum custody, and plumbing (loopback RPC, file locks, logger, sidebar state, TUI preferences and build).",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|
|
@@ -24,6 +24,10 @@
|
|
|
24
24
|
"types": "./dist/fs/index.d.ts",
|
|
25
25
|
"import": "./dist/fs/index.js"
|
|
26
26
|
},
|
|
27
|
+
"./pi-slot": {
|
|
28
|
+
"types": "./dist/pi-slot/index.d.ts",
|
|
29
|
+
"import": "./dist/pi-slot/index.js"
|
|
30
|
+
},
|
|
27
31
|
"./logger": {
|
|
28
32
|
"types": "./dist/logger/index.d.ts",
|
|
29
33
|
"import": "./dist/logger/index.js"
|
|
@@ -127,6 +131,7 @@
|
|
|
127
131
|
"devDependencies": {
|
|
128
132
|
"@biomejs/biome": "2.5.14",
|
|
129
133
|
"@cortexkit/claustrum-client": "0.6.2",
|
|
134
|
+
"@earendil-works/pi-coding-agent": "1.0.4",
|
|
130
135
|
"@opencode/plugin": "2.0.21",
|
|
131
136
|
"@opentui/core": ">=0.5.12",
|
|
132
137
|
"@opentui/solid": ">=0.5.12",
|
|
@@ -135,6 +140,7 @@
|
|
|
135
140
|
"bun-types": "1.4.2",
|
|
136
141
|
"inline-default": "workspace:*",
|
|
137
142
|
"lefthook": "2.1.14",
|
|
143
|
+
"proper-lockfile": "4.1.2",
|
|
138
144
|
"solid-js": "1.9.12",
|
|
139
145
|
"typescript": "7.0.2"
|
|
140
146
|
}
|