@composable-os/cli 0.1.0-beta.8 → 0.1.0-beta.9
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/accounts-D6N77JGP.js +44 -0
- package/dist/{blocks-DEELKGDC.js → blocks-4CA4PP3P.js} +4 -4
- package/dist/{chunk-X6I2LWB3.js → chunk-2MLAPQU7.js} +1471 -359
- package/dist/{chunk-2S7375SC.js → chunk-3MIEYXRY.js} +3 -301
- package/dist/chunk-56A6RJIU.js +1040 -0
- package/dist/chunk-7CQGMVDO.js +63 -0
- package/dist/{chunk-STJZJIRA.js → chunk-7O4F3NU4.js} +1039 -1380
- package/dist/chunk-7U3OZLTK.js +1370 -0
- package/dist/{chunk-ZRWF6QZS.js → chunk-DU6OIFOU.js} +1 -0
- package/dist/chunk-E4WCYTCT.js +347 -0
- package/dist/{chunk-E5JLTLRM.js → chunk-GYTEW66E.js} +1 -1
- package/dist/chunk-LPD2VR5M.js +284 -0
- package/dist/chunk-NDKVIG23.js +2641 -0
- package/dist/chunk-NSSUOI3Z.js +333 -0
- package/dist/chunk-OV3OFYPI.js +746 -0
- package/dist/{chunk-KTXGEXTY.js → chunk-P6YZMS3F.js} +11 -5
- package/dist/{chunk-G3ORKXVP.js → chunk-RFJOPI42.js} +138 -14
- package/dist/{chunk-KOKYDJ7Z.js → chunk-RXRD34QW.js} +10 -8
- package/dist/{chunk-XDDBLYKW.js → chunk-STBMGUTM.js} +4613 -2307
- package/dist/chunk-VTQNOQGA.js +150 -0
- package/dist/chunk-XSE37HK5.js +426 -0
- package/dist/{chunk-LTQDLCP7.js → chunk-Z52IX5WL.js} +257 -845
- package/dist/chunk-ZSR5H4O7.js +552 -0
- package/dist/{cli-DTMGNDXN.js → cli-7A5XHYML.js} +16 -9
- package/dist/{cli-BRSACHSG.js → cli-T6MJM7TU.js} +20 -8
- package/dist/cli.js +4 -4
- package/dist/{client-repo-ZVZ6KW5S.js → client-repo-PC4ISVEZ.js} +4 -4
- package/dist/create.js +4 -4
- package/dist/{fields-64BQJA62.js → fields-L24XAIOA.js} +13 -11
- package/dist/invoke-TLYT6CFI.js +33 -0
- package/dist/order-IKQBUFCV.js +19 -0
- package/dist/{person-WMWRF2HV.js → person-DXEOOH2A.js} +9 -5
- package/dist/plan-on-sale-LRCK5MJG.js +24 -0
- package/dist/platform/migrations/0510_video_and_file_media.sql +109 -0
- package/dist/platform/migrations/0516_order_tax.sql +63 -0
- package/dist/platform/migrations/0530_subscriptions.sql +173 -0
- package/dist/platform/migrations/0531_subscription_trials.sql +56 -0
- package/dist/platform/migrations/0532_subscription_offers.sql +80 -0
- package/dist/platform/migrations/0533_allowances.sql +262 -0
- package/dist/platform/migrations/0560_recurring.sql +75 -0
- package/dist/platform/sdk/allowance.ts +508 -0
- package/dist/platform/sdk/capacity.ts +89 -0
- package/dist/platform/sdk/contract.ts +97 -1
- package/dist/platform/sdk/document.ts +161 -14
- package/dist/platform/sdk/field-types.ts +5 -0
- package/dist/platform/sdk/index.ts +3 -0
- package/dist/platform/sdk/manifest.ts +206 -5
- package/dist/platform/sdk/media.ts +62 -0
- package/dist/platform/sdk/recurring.ts +314 -0
- package/dist/platform/sdk/rich-text.ts +52 -4
- package/dist/platform/sdk/sellable.ts +120 -0
- package/dist/platform/sdk/states.ts +162 -1
- package/dist/platform/sdk/unique.ts +81 -0
- package/dist/run-BMSZKTN3.js +648 -0
- package/dist/run-GMQBAV6H.js +309 -0
- package/dist/{run-4JNFLYXV.js → run-TNHMG5RI.js} +51 -390
- package/dist/src-7DXXGZG2.js +38 -0
- package/dist/{src-J27WXNLY.js → src-BDG7PERB.js} +73 -1
- package/dist/visibility-XSBZTO66.js +33 -0
- package/package.json +2 -2
- package/dist/chunk-MAXLUQKB.js +0 -1287
- package/dist/invoke-NHHOLLF6.js +0 -26
- package/dist/src-G6OF5SKW.js +0 -31
|
@@ -1112,6 +1112,7 @@ function workerBindings(worker, manifest, state, secrets) {
|
|
|
1112
1112
|
return binding;
|
|
1113
1113
|
});
|
|
1114
1114
|
for (const [name, text] of Object.entries(overrides)) {
|
|
1115
|
+
if ((worker.secrets ?? []).some((s) => s.name === name)) continue;
|
|
1115
1116
|
if (!bindings.some((b) => b.name === name)) bindings.push({ type: "plain_text", name, text });
|
|
1116
1117
|
}
|
|
1117
1118
|
if (worker.gatekeeperBindings) {
|
|
@@ -0,0 +1,347 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
|
|
3
|
+
// src/import-door/sign-in.ts
|
|
4
|
+
import { execFile } from "node:child_process";
|
|
5
|
+
import { createServer } from "node:http";
|
|
6
|
+
import { hostname } from "node:os";
|
|
7
|
+
|
|
8
|
+
// ../client/src/binding.ts
|
|
9
|
+
var SESSION_CHECK_INTERVAL_MS = 24 * 60 * 60 * 1e3;
|
|
10
|
+
|
|
11
|
+
// ../client/src/errors.ts
|
|
12
|
+
var ApiError = class extends Error {
|
|
13
|
+
constructor(code, message, status, details) {
|
|
14
|
+
super(message);
|
|
15
|
+
this.code = code;
|
|
16
|
+
this.status = status;
|
|
17
|
+
this.details = details;
|
|
18
|
+
}
|
|
19
|
+
code;
|
|
20
|
+
status;
|
|
21
|
+
details;
|
|
22
|
+
name = "ApiError";
|
|
23
|
+
};
|
|
24
|
+
var NetworkError = class extends Error {
|
|
25
|
+
constructor(message, cause) {
|
|
26
|
+
super(message);
|
|
27
|
+
this.cause = cause;
|
|
28
|
+
}
|
|
29
|
+
cause;
|
|
30
|
+
name = "NetworkError";
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
// ../client/src/session.ts
|
|
34
|
+
async function post(fetcher, url, body, headers = {}) {
|
|
35
|
+
let response;
|
|
36
|
+
try {
|
|
37
|
+
response = await fetcher(url, {
|
|
38
|
+
method: "POST",
|
|
39
|
+
headers: { "content-type": "application/json", ...headers },
|
|
40
|
+
body: JSON.stringify(body)
|
|
41
|
+
});
|
|
42
|
+
} catch (error) {
|
|
43
|
+
throw new NetworkError("Could not reach the host to sign in", error);
|
|
44
|
+
}
|
|
45
|
+
const parsed = JSON.parse(await response.text());
|
|
46
|
+
if (response.status === 200 && parsed.data) return parsed.data;
|
|
47
|
+
throw new ApiError(
|
|
48
|
+
parsed.error?.code ?? "internal",
|
|
49
|
+
parsed.error?.message ?? `The host answered ${response.status}`,
|
|
50
|
+
response.status,
|
|
51
|
+
parsed.error?.details
|
|
52
|
+
);
|
|
53
|
+
}
|
|
54
|
+
function tokenSession(options) {
|
|
55
|
+
const base = options.baseUrl.replace(/\/+$/, "");
|
|
56
|
+
const fetcher = options.fetch ?? globalThis.fetch?.bind(globalThis);
|
|
57
|
+
const early = options.refreshEarlyMs ?? 3e4;
|
|
58
|
+
const now = options.now ?? (() => Date.now());
|
|
59
|
+
let refreshing = null;
|
|
60
|
+
async function refresh(tokens) {
|
|
61
|
+
try {
|
|
62
|
+
const next = await post(fetcher, `${base}/api/v1/auth/refresh`, {
|
|
63
|
+
refreshToken: tokens.refreshToken
|
|
64
|
+
});
|
|
65
|
+
await options.store.save(next);
|
|
66
|
+
return next;
|
|
67
|
+
} catch (error) {
|
|
68
|
+
if (error instanceof ApiError) await options.store.save(null);
|
|
69
|
+
throw error;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
return {
|
|
73
|
+
/**
|
|
74
|
+
* Exchanges a sign-in for tokens. `credentials` are the headers that carry it, such as the
|
|
75
|
+
* cookie the sign-in answered with.
|
|
76
|
+
*/
|
|
77
|
+
async exchange(deviceName, credentials) {
|
|
78
|
+
const tokens = await post(fetcher, `${base}/api/v1/auth/token`, { deviceName }, credentials);
|
|
79
|
+
await options.store.save(tokens);
|
|
80
|
+
return tokens;
|
|
81
|
+
},
|
|
82
|
+
/**
|
|
83
|
+
* Asks the host to email a sign-in code (ADR 0455). The answer is the same whoever the
|
|
84
|
+
* address is; it throws only when the host refuses to send any (`rate_limited`, or sign-in
|
|
85
|
+
* not set up).
|
|
86
|
+
*/
|
|
87
|
+
async requestCode(email, audience = "customer") {
|
|
88
|
+
await post(fetcher, `${base}/api/v1/auth/${audience}/code`, { email });
|
|
89
|
+
},
|
|
90
|
+
/**
|
|
91
|
+
* Signs in with the emailed code and keeps the device session the host answers with. A wrong,
|
|
92
|
+
* used or expired code throws `forbidden` (`invalid_code`). No cookie is involved.
|
|
93
|
+
*/
|
|
94
|
+
async signInWithCode(email, code, deviceName, audience = "customer") {
|
|
95
|
+
const signedIn = await post(fetcher, `${base}/api/v1/auth/${audience}/sign-in`, {
|
|
96
|
+
email,
|
|
97
|
+
code,
|
|
98
|
+
deviceName
|
|
99
|
+
});
|
|
100
|
+
const { account: _account, ...tokens } = signedIn;
|
|
101
|
+
await options.store.save(tokens);
|
|
102
|
+
return signedIn;
|
|
103
|
+
},
|
|
104
|
+
/**
|
|
105
|
+
* Finishes a staff sign-in in the system browser (`startBrowserSignIn`): checks the state it
|
|
106
|
+
* was sent back with and exchanges the code, with the verifier, for a device session.
|
|
107
|
+
*/
|
|
108
|
+
async finishBrowserSignIn(input) {
|
|
109
|
+
const query = input.callbackUrl.includes("?") ? input.callbackUrl.split("?")[1] ?? "" : "";
|
|
110
|
+
const params = new Map(
|
|
111
|
+
query.split("&").filter(Boolean).map((pair) => {
|
|
112
|
+
const [key = "", value = ""] = pair.split("=");
|
|
113
|
+
return [decodeURIComponent(key), decodeURIComponent(value.replace(/\+/g, " "))];
|
|
114
|
+
})
|
|
115
|
+
);
|
|
116
|
+
const code = params.get("code");
|
|
117
|
+
if (!code || params.get("state") !== input.state) {
|
|
118
|
+
throw new ApiError(
|
|
119
|
+
"forbidden",
|
|
120
|
+
"The sign-in did not come back from this app's request",
|
|
121
|
+
401,
|
|
122
|
+
{
|
|
123
|
+
reason: "invalid_code"
|
|
124
|
+
}
|
|
125
|
+
);
|
|
126
|
+
}
|
|
127
|
+
const tokens = await post(fetcher, `${base}/api/v1/auth/staff/exchange`, {
|
|
128
|
+
code,
|
|
129
|
+
codeVerifier: input.verifier,
|
|
130
|
+
redirectUri: input.redirectUri,
|
|
131
|
+
deviceName: input.deviceName
|
|
132
|
+
});
|
|
133
|
+
await options.store.save(tokens);
|
|
134
|
+
return tokens;
|
|
135
|
+
},
|
|
136
|
+
/** The headers for a call: a current access token, refreshed first when it is about to end. */
|
|
137
|
+
async headers() {
|
|
138
|
+
let tokens = await options.store.load();
|
|
139
|
+
if (!tokens) return {};
|
|
140
|
+
if (Date.parse(tokens.accessExpiresAt) - early <= now()) {
|
|
141
|
+
refreshing ??= refresh(tokens).finally(() => {
|
|
142
|
+
refreshing = null;
|
|
143
|
+
});
|
|
144
|
+
tokens = await refreshing;
|
|
145
|
+
if (!tokens) return {};
|
|
146
|
+
}
|
|
147
|
+
return { authorization: `Bearer ${tokens.accessToken}` };
|
|
148
|
+
},
|
|
149
|
+
/**
|
|
150
|
+
* Ends this device's session on the host (ADR 0455) with its refresh token, which any account
|
|
151
|
+
* may do whatever it may call, then forgets the tokens, even when the host could not be
|
|
152
|
+
* reached.
|
|
153
|
+
*/
|
|
154
|
+
async signOut() {
|
|
155
|
+
const tokens = await options.store.load();
|
|
156
|
+
try {
|
|
157
|
+
if (tokens) {
|
|
158
|
+
await post(fetcher, `${base}/api/v1/auth/sign-out`, {
|
|
159
|
+
refreshToken: tokens.refreshToken
|
|
160
|
+
});
|
|
161
|
+
}
|
|
162
|
+
} catch {
|
|
163
|
+
} finally {
|
|
164
|
+
await options.store.save(null);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
function base64url(bytes) {
|
|
170
|
+
const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
|
|
171
|
+
let out = "";
|
|
172
|
+
for (let i = 0; i < bytes.length; i += 3) {
|
|
173
|
+
const a = bytes[i] ?? 0;
|
|
174
|
+
const b = bytes[i + 1];
|
|
175
|
+
const c = bytes[i + 2];
|
|
176
|
+
out += alphabet[a >> 2];
|
|
177
|
+
out += alphabet[(a & 3) << 4 | (b ?? 0) >> 4];
|
|
178
|
+
if (b !== void 0) out += alphabet[(b & 15) << 2 | (c ?? 0) >> 6];
|
|
179
|
+
if (c !== void 0) out += alphabet[c & 63];
|
|
180
|
+
}
|
|
181
|
+
return out;
|
|
182
|
+
}
|
|
183
|
+
async function startBrowserSignIn(options) {
|
|
184
|
+
const verifier = `${options.randomKey()}${options.randomKey()}`.replace(/[^A-Za-z0-9._~-]/g, "").slice(0, 128);
|
|
185
|
+
if (verifier.length < 43) throw new Error("randomKey must give at least 22 characters");
|
|
186
|
+
const state = options.randomKey().replace(/[^A-Za-z0-9._~-]/g, "");
|
|
187
|
+
const challenge = base64url(await options.sha256(verifier));
|
|
188
|
+
const query = [
|
|
189
|
+
["redirect_uri", options.redirectUri],
|
|
190
|
+
["code_challenge", challenge],
|
|
191
|
+
["code_challenge_method", "S256"],
|
|
192
|
+
["state", state]
|
|
193
|
+
].map(([k, v]) => `${k}=${encodeURIComponent(v)}`).join("&");
|
|
194
|
+
return {
|
|
195
|
+
url: `${options.hostUrl.replace(/\/+$/, "")}/native/staff-sign-in?${query}`,
|
|
196
|
+
state,
|
|
197
|
+
verifier
|
|
198
|
+
};
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
// src/import-door/sign-in.ts
|
|
202
|
+
var LOOPBACK_PATH = "/cos-sign-in";
|
|
203
|
+
function memoryStore() {
|
|
204
|
+
let saved = null;
|
|
205
|
+
return {
|
|
206
|
+
load: async () => saved,
|
|
207
|
+
save: async (tokens) => {
|
|
208
|
+
saved = tokens;
|
|
209
|
+
}
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
var hex = (bytes) => [...bytes].map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
213
|
+
function openBrowser(url, io) {
|
|
214
|
+
io.out(`Sign in in your browser: ${url}`);
|
|
215
|
+
const command = process.platform === "darwin" ? "open" : process.platform === "win32" ? "explorer" : "xdg-open";
|
|
216
|
+
execFile(command, [url], () => {
|
|
217
|
+
});
|
|
218
|
+
}
|
|
219
|
+
async function loopback() {
|
|
220
|
+
let settle;
|
|
221
|
+
const callback = new Promise((resolve_) => {
|
|
222
|
+
settle = resolve_;
|
|
223
|
+
});
|
|
224
|
+
const server = createServer((req, res) => {
|
|
225
|
+
const url = new URL(req.url ?? "/", "http://127.0.0.1");
|
|
226
|
+
if (url.pathname !== LOOPBACK_PATH) {
|
|
227
|
+
res.writeHead(404).end();
|
|
228
|
+
return;
|
|
229
|
+
}
|
|
230
|
+
res.writeHead(200, { "content-type": "text/plain; charset=utf-8" }).end("Signed in. You can close this tab and go back to the terminal.");
|
|
231
|
+
settle(`http://127.0.0.1${req.url}`);
|
|
232
|
+
});
|
|
233
|
+
await new Promise((done) => server.listen(0, "127.0.0.1", done));
|
|
234
|
+
const port = server.address().port;
|
|
235
|
+
return {
|
|
236
|
+
redirectUri: `http://127.0.0.1:${port}${LOOPBACK_PATH}`,
|
|
237
|
+
callback,
|
|
238
|
+
close: () => server.close()
|
|
239
|
+
};
|
|
240
|
+
}
|
|
241
|
+
async function signInForRun(host, email, io, label) {
|
|
242
|
+
const session = tokenSession({ baseUrl: host, store: memoryStore() });
|
|
243
|
+
const deviceName = `${label} on ${hostname()}`.slice(0, 100);
|
|
244
|
+
if (email) {
|
|
245
|
+
await session.requestCode(email, "staff");
|
|
246
|
+
io.out(
|
|
247
|
+
`If ${email} may sign in by code, a code is on its way. If none arrives in a minute or two, check on the host: the address is one an admin invited, or one you confirmed (your account menu, Confirm your email), and Settings \u2192 Users shows sign-in codes going out (Send sign-in codes without review). Or run without --email to sign in with the browser.`
|
|
248
|
+
);
|
|
249
|
+
const code = await io.ask(`The sign-in code sent to ${email}`, { secret: true });
|
|
250
|
+
await session.signInWithCode(email, code.trim(), deviceName, "staff");
|
|
251
|
+
return session;
|
|
252
|
+
}
|
|
253
|
+
const back = await loopback();
|
|
254
|
+
try {
|
|
255
|
+
const random = () => hex(crypto.getRandomValues(new Uint8Array(16)));
|
|
256
|
+
const started = await startBrowserSignIn({
|
|
257
|
+
hostUrl: host,
|
|
258
|
+
redirectUri: back.redirectUri,
|
|
259
|
+
randomKey: random,
|
|
260
|
+
sha256: async (text) => new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text)))
|
|
261
|
+
});
|
|
262
|
+
openBrowser(started.url, io);
|
|
263
|
+
const callbackUrl = await back.callback;
|
|
264
|
+
await session.finishBrowserSignIn({
|
|
265
|
+
callbackUrl,
|
|
266
|
+
state: started.state,
|
|
267
|
+
verifier: started.verifier,
|
|
268
|
+
redirectUri: back.redirectUri,
|
|
269
|
+
deviceName
|
|
270
|
+
});
|
|
271
|
+
return session;
|
|
272
|
+
} finally {
|
|
273
|
+
back.close();
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
function confirmer(io, yes) {
|
|
277
|
+
return async (summary) => {
|
|
278
|
+
if (yes) return true;
|
|
279
|
+
if (!io.interactive) {
|
|
280
|
+
io.err(`${summary}. Pass --yes to confirm it when running from a script.`);
|
|
281
|
+
return false;
|
|
282
|
+
}
|
|
283
|
+
const answer = await io.ask(`${summary}. Go ahead? (yes/no)`, { default: "no" });
|
|
284
|
+
return /^y(es)?$/i.test(answer.trim());
|
|
285
|
+
};
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
// src/import-door/host.ts
|
|
289
|
+
async function readError(response) {
|
|
290
|
+
const body = await response.json().catch(() => ({}));
|
|
291
|
+
return body.error?.message ?? `HTTP ${response.status}`;
|
|
292
|
+
}
|
|
293
|
+
function sessionHost(base, headers, fetcher = fetch, outside = fetcher) {
|
|
294
|
+
return {
|
|
295
|
+
async call(name, input) {
|
|
296
|
+
const response = await fetcher(`${base}/api/v1/op/${encodeURIComponent(name)}`, {
|
|
297
|
+
method: "POST",
|
|
298
|
+
headers: {
|
|
299
|
+
"content-type": "application/json",
|
|
300
|
+
"idempotency-key": crypto.randomUUID(),
|
|
301
|
+
...await headers()
|
|
302
|
+
},
|
|
303
|
+
body: JSON.stringify(input)
|
|
304
|
+
});
|
|
305
|
+
const body = await response.json();
|
|
306
|
+
if (!response.ok || body.error) {
|
|
307
|
+
throw Object.assign(new Error(body.error?.message ?? `${name}: HTTP ${response.status}`), {
|
|
308
|
+
code: body.error?.code,
|
|
309
|
+
details: body.error?.details
|
|
310
|
+
});
|
|
311
|
+
}
|
|
312
|
+
return body.data;
|
|
313
|
+
},
|
|
314
|
+
async upload(bytes, name) {
|
|
315
|
+
const response = await fetcher(`${base}/api/v1/media?${new URLSearchParams({ name })}`, {
|
|
316
|
+
method: "POST",
|
|
317
|
+
headers: { "content-type": "application/octet-stream", ...await headers() },
|
|
318
|
+
body: new Uint8Array(bytes)
|
|
319
|
+
});
|
|
320
|
+
const body = await response.json();
|
|
321
|
+
if (!response.ok || !body.data) {
|
|
322
|
+
throw new Error(`${name}: ${body.error?.message ?? `HTTP ${response.status}`}`);
|
|
323
|
+
}
|
|
324
|
+
return body.data;
|
|
325
|
+
},
|
|
326
|
+
async uploadCaption(id, language, label, vtt) {
|
|
327
|
+
const query = new URLSearchParams({ language, label });
|
|
328
|
+
const response = await fetcher(
|
|
329
|
+
`${base}/api/v1/media/${encodeURIComponent(id)}/captions?${query}`,
|
|
330
|
+
{
|
|
331
|
+
method: "POST",
|
|
332
|
+
headers: { "content-type": "text/vtt", ...await headers() },
|
|
333
|
+
body: new Uint8Array(vtt)
|
|
334
|
+
}
|
|
335
|
+
);
|
|
336
|
+
if (!response.ok) throw new Error(`captions (${language}): ${await readError(response)}`);
|
|
337
|
+
},
|
|
338
|
+
send: (url, init) => outside(url, init)
|
|
339
|
+
};
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
export {
|
|
343
|
+
LOOPBACK_PATH,
|
|
344
|
+
signInForRun,
|
|
345
|
+
confirmer,
|
|
346
|
+
sessionHost
|
|
347
|
+
};
|
|
@@ -0,0 +1,284 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {
|
|
3
|
+
checkPerson,
|
|
4
|
+
erasedAddresses
|
|
5
|
+
} from "./chunk-Z52IX5WL.js";
|
|
6
|
+
import {
|
|
7
|
+
notifyStatements
|
|
8
|
+
} from "./chunk-56A6RJIU.js";
|
|
9
|
+
import {
|
|
10
|
+
newId
|
|
11
|
+
} from "./chunk-OV3OFYPI.js";
|
|
12
|
+
import {
|
|
13
|
+
ConfigError,
|
|
14
|
+
ConflictError,
|
|
15
|
+
NotFoundError,
|
|
16
|
+
ValidationError
|
|
17
|
+
} from "./chunk-7O4F3NU4.js";
|
|
18
|
+
import {
|
|
19
|
+
external_exports
|
|
20
|
+
} from "./chunk-2MLAPQU7.js";
|
|
21
|
+
|
|
22
|
+
// ../core/src/customers/settings.ts
|
|
23
|
+
var CUSTOMER_SIGNUP_SETTING = "customer_signup";
|
|
24
|
+
var CUSTOMER_SIGNUP_MODES = ["open", "buyers", "invite_only"];
|
|
25
|
+
var customerSignupModeSchema = external_exports.enum(CUSTOMER_SIGNUP_MODES);
|
|
26
|
+
var DEFAULT_CUSTOMER_SIGNUP = "invite_only";
|
|
27
|
+
async function loadCustomerSignup(db) {
|
|
28
|
+
const row = await db.selectFrom("core_settings").select("value").where("key", "=", CUSTOMER_SIGNUP_SETTING).executeTakeFirst();
|
|
29
|
+
if (!row) return DEFAULT_CUSTOMER_SIGNUP;
|
|
30
|
+
try {
|
|
31
|
+
const parsed = customerSignupModeSchema.safeParse(JSON.parse(row.value));
|
|
32
|
+
return parsed.success ? parsed.data : DEFAULT_CUSTOMER_SIGNUP;
|
|
33
|
+
} catch {
|
|
34
|
+
return DEFAULT_CUSTOMER_SIGNUP;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
var CUSTOMER_SIGNUP_SUBSCRIBERS_SETTING = "customer_signup_subscribers";
|
|
38
|
+
var DEFAULT_CUSTOMER_SIGNUP_SUBSCRIBERS = false;
|
|
39
|
+
async function loadCustomerSignupSubscribers(db) {
|
|
40
|
+
const row = await db.selectFrom("core_settings").select("value").where("key", "=", CUSTOMER_SIGNUP_SUBSCRIBERS_SETTING).executeTakeFirst();
|
|
41
|
+
if (!row) return DEFAULT_CUSTOMER_SIGNUP_SUBSCRIBERS;
|
|
42
|
+
try {
|
|
43
|
+
return JSON.parse(row.value) === true;
|
|
44
|
+
} catch {
|
|
45
|
+
return DEFAULT_CUSTOMER_SIGNUP_SUBSCRIBERS;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
var CUSTOMER_ERASE_DUE_SETTING = "customer_erase_due_days";
|
|
49
|
+
var DEFAULT_ERASE_DUE_DAYS = 30;
|
|
50
|
+
var eraseDueDaysSchema = external_exports.number().int().min(1).max(365);
|
|
51
|
+
async function loadEraseDueDays(db) {
|
|
52
|
+
const row = await db.selectFrom("core_settings").select("value").where("key", "=", CUSTOMER_ERASE_DUE_SETTING).executeTakeFirst();
|
|
53
|
+
if (!row) return DEFAULT_ERASE_DUE_DAYS;
|
|
54
|
+
try {
|
|
55
|
+
const parsed = eraseDueDaysSchema.safeParse(JSON.parse(row.value));
|
|
56
|
+
return parsed.success ? parsed.data : DEFAULT_ERASE_DUE_DAYS;
|
|
57
|
+
} catch {
|
|
58
|
+
return DEFAULT_ERASE_DUE_DAYS;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
var CUSTOMER_EMAIL_CONNECTION_SETTING = "customer_email_connection";
|
|
62
|
+
async function loadCustomerEmailConnection(db) {
|
|
63
|
+
const row = await db.selectFrom("core_settings").select("value").where("key", "=", CUSTOMER_EMAIL_CONNECTION_SETTING).executeTakeFirst();
|
|
64
|
+
if (!row) return null;
|
|
65
|
+
try {
|
|
66
|
+
const value = JSON.parse(row.value);
|
|
67
|
+
return typeof value === "string" && value ? value : null;
|
|
68
|
+
} catch {
|
|
69
|
+
return null;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// ../core/src/customers/accounts.ts
|
|
74
|
+
var emailSchema = external_exports.string().trim().toLowerCase().pipe(external_exports.email().max(320));
|
|
75
|
+
function normaliseCustomerEmail(email) {
|
|
76
|
+
const parsed = emailSchema.safeParse(email);
|
|
77
|
+
return parsed.success ? parsed.data : null;
|
|
78
|
+
}
|
|
79
|
+
function toAccount(row) {
|
|
80
|
+
return {
|
|
81
|
+
id: row.id,
|
|
82
|
+
personId: row.person_id,
|
|
83
|
+
email: row.email,
|
|
84
|
+
status: row.status,
|
|
85
|
+
linkState: row.link_state
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
var ACCOUNT_COLUMNS = ["id", "person_id", "email", "status", "link_state"];
|
|
89
|
+
async function loadCustomer(db, id) {
|
|
90
|
+
const row = await db.selectFrom("core_customer").select(ACCOUNT_COLUMNS).where("id", "=", id).executeTakeFirst();
|
|
91
|
+
return row ? toAccount(row) : null;
|
|
92
|
+
}
|
|
93
|
+
async function loadCustomerSignIn(db, customerId, personId) {
|
|
94
|
+
const row = await db.selectFrom("core_customer").select(["email", "email_verified"]).where("id", "=", customerId).where("person_id", "=", personId).where("status", "=", "active").executeTakeFirst();
|
|
95
|
+
return row ? { email: row.email, verified: row.email_verified === 1 } : null;
|
|
96
|
+
}
|
|
97
|
+
async function loadCustomerByEmail(db, email) {
|
|
98
|
+
const address = normaliseCustomerEmail(email);
|
|
99
|
+
if (!address) return null;
|
|
100
|
+
const row = await db.selectFrom("core_customer").select(ACCOUNT_COLUMNS).where("email", "=", address).executeTakeFirst();
|
|
101
|
+
return row ? toAccount(row) : null;
|
|
102
|
+
}
|
|
103
|
+
async function isErased(db, address) {
|
|
104
|
+
return (await erasedAddresses(db, [address])).size > 0;
|
|
105
|
+
}
|
|
106
|
+
async function customerCodeReason(db, email, now = (/* @__PURE__ */ new Date()).toISOString(), options = {}) {
|
|
107
|
+
const address = normaliseCustomerEmail(email);
|
|
108
|
+
if (!address) return null;
|
|
109
|
+
if (await isErased(db, address)) return null;
|
|
110
|
+
const account = await loadCustomerByEmail(db, address);
|
|
111
|
+
if (account) return account.status === "active" ? "account" : null;
|
|
112
|
+
const signup = await loadCustomerSignup(db);
|
|
113
|
+
if (signup === "open") return "open";
|
|
114
|
+
const invite = await db.selectFrom("core_customer_invite").select("email").where("email", "=", address).executeTakeFirst();
|
|
115
|
+
if (invite) return "invite";
|
|
116
|
+
if (signup === "buyers" && await hasBought(db, address)) return "buyer";
|
|
117
|
+
if (await loadCustomerSignupSubscribers(db)) {
|
|
118
|
+
const { findPlanOnSale } = await import("./plan-on-sale-LRCK5MJG.js");
|
|
119
|
+
const found = await findPlanOnSale(db, now, options);
|
|
120
|
+
if (found.state === "on_sale") return "subscription";
|
|
121
|
+
}
|
|
122
|
+
return null;
|
|
123
|
+
}
|
|
124
|
+
async function customerMayGetCode(db, email) {
|
|
125
|
+
return await customerCodeReason(db, email) !== null;
|
|
126
|
+
}
|
|
127
|
+
async function hasBought(db, address) {
|
|
128
|
+
const { orgReader, visibleSource } = await import("./visibility-XSBZTO66.js");
|
|
129
|
+
const { orderObject } = await import("./order-IKQBUFCV.js");
|
|
130
|
+
const owners = db.selectFrom("core_person_emails as e").innerJoin("core_person as p", "p.id", "e.person_id").select("e.person_id").where("e.email", "=", address).where("e.live", "=", 1).where("p.deleted_at", "is", null);
|
|
131
|
+
const row = await db.selectFrom(visibleSource(orgReader(db), orderObject)).select("id").where((eb) => eb.or([eb("email", "=", address), eb("person_id", "in", owners)])).where("paid", ">", 0).executeTakeFirst();
|
|
132
|
+
return Boolean(row);
|
|
133
|
+
}
|
|
134
|
+
async function inviteCustomerStatement(db, email, invitedByUserId, now) {
|
|
135
|
+
const address = normaliseCustomerEmail(email);
|
|
136
|
+
if (!address) throw new ValidationError("Not an email address", { field: "email" });
|
|
137
|
+
if (await isErased(db, address)) {
|
|
138
|
+
throw new ValidationError("This address belongs to an erased person", { field: "email" });
|
|
139
|
+
}
|
|
140
|
+
const statement = db.insertInto("core_customer_invite").values({ email: address, invited_by: invitedByUserId, invited_at: now }).onConflict(
|
|
141
|
+
(oc) => oc.column("email").doUpdateSet({ invited_by: invitedByUserId, invited_at: now })
|
|
142
|
+
);
|
|
143
|
+
return { email: address, statement };
|
|
144
|
+
}
|
|
145
|
+
async function inviteCustomer(db, email, invitedByUserId, now = (/* @__PURE__ */ new Date()).toISOString()) {
|
|
146
|
+
const { email: address, statement } = await inviteCustomerStatement(
|
|
147
|
+
db.query,
|
|
148
|
+
email,
|
|
149
|
+
invitedByUserId,
|
|
150
|
+
now
|
|
151
|
+
);
|
|
152
|
+
await db.batch([statement]);
|
|
153
|
+
return { email: address };
|
|
154
|
+
}
|
|
155
|
+
var CUSTOMER_LINK_AUDIT = "customer.link";
|
|
156
|
+
async function sameEmailPeople(db, address) {
|
|
157
|
+
const { conflicts } = await checkPerson(db, { emails: [address] });
|
|
158
|
+
return [...new Set(conflicts.map((c) => c.id))];
|
|
159
|
+
}
|
|
160
|
+
async function creatorFor(db, address) {
|
|
161
|
+
const active = db.selectFrom("core_user").select(["id", "email", "name", "role"]).where("kind", "=", "human").where("deactivated_at", "is", null);
|
|
162
|
+
const invite = await db.selectFrom("core_customer_invite").select("invited_by").where("email", "=", address).executeTakeFirst();
|
|
163
|
+
const row = (invite ? await active.where("id", "=", invite.invited_by).executeTakeFirst() : void 0) ?? await active.where("role", "=", "admin").orderBy("id").limit(1).executeTakeFirst();
|
|
164
|
+
return row ? { id: row.id, email: row.email, name: row.name, role: row.role } : null;
|
|
165
|
+
}
|
|
166
|
+
async function createPersonFor(db, address, customerId, now) {
|
|
167
|
+
const user = await creatorFor(db.query, address);
|
|
168
|
+
if (!user) throw new ConfigError("There is no admin to create the customer's Person for");
|
|
169
|
+
const { invoke } = await import("./invoke-TLYT6CFI.js");
|
|
170
|
+
const person = await invoke(
|
|
171
|
+
"person.create",
|
|
172
|
+
{ emails: [{ email: address, primary: true }] },
|
|
173
|
+
{
|
|
174
|
+
actor: "automation",
|
|
175
|
+
user,
|
|
176
|
+
origin: { surface: "system", automationId: CUSTOMER_LINK_AUDIT, sessionId: customerId },
|
|
177
|
+
db,
|
|
178
|
+
clock: () => now
|
|
179
|
+
}
|
|
180
|
+
);
|
|
181
|
+
return person.id;
|
|
182
|
+
}
|
|
183
|
+
async function linkCustomer(db, customerId, now = /* @__PURE__ */ new Date()) {
|
|
184
|
+
const account = await loadCustomer(db.query, customerId);
|
|
185
|
+
if (!account) throw new NotFoundError("customer", customerId);
|
|
186
|
+
if (account.personId && account.linkState === "linked") {
|
|
187
|
+
return { linkState: "linked", personId: account.personId, created: false };
|
|
188
|
+
}
|
|
189
|
+
if (await isErased(db.query, account.email)) {
|
|
190
|
+
throw new ValidationError("This address belongs to an erased person");
|
|
191
|
+
}
|
|
192
|
+
let matches = await sameEmailPeople(db.query, account.email);
|
|
193
|
+
let created = false;
|
|
194
|
+
if (matches.length === 0) {
|
|
195
|
+
try {
|
|
196
|
+
matches = [await createPersonFor(db, account.email, account.id, now)];
|
|
197
|
+
created = true;
|
|
198
|
+
} catch (error) {
|
|
199
|
+
if (!(error instanceof ConflictError)) throw error;
|
|
200
|
+
matches = await sameEmailPeople(db.query, account.email);
|
|
201
|
+
if (!matches.length) throw error;
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
let result;
|
|
205
|
+
if (matches.length === 1) {
|
|
206
|
+
const personId = matches[0];
|
|
207
|
+
const holder = await db.query.selectFrom("core_customer").select("id").where("person_id", "=", personId).where("id", "!=", account.id).executeTakeFirst();
|
|
208
|
+
result = holder ? { linkState: "needs_merge", personId: null, created, reason: "person_has_account" } : { linkState: "linked", personId, created };
|
|
209
|
+
} else {
|
|
210
|
+
result = { linkState: "needs_merge", personId: null, created, reason: "several_people" };
|
|
211
|
+
}
|
|
212
|
+
const at = now.toISOString();
|
|
213
|
+
const statements = [
|
|
214
|
+
db.query.updateTable("core_customer").set({ person_id: result.personId, link_state: result.linkState, updated_at: at }).where("id", "=", account.id),
|
|
215
|
+
db.query.insertInto("core_audit").values({
|
|
216
|
+
id: newId("audit"),
|
|
217
|
+
at,
|
|
218
|
+
operation: CUSTOMER_LINK_AUDIT,
|
|
219
|
+
risk: "write",
|
|
220
|
+
actor: "customer",
|
|
221
|
+
user_id: account.id,
|
|
222
|
+
origin: JSON.stringify({ surface: "client" }),
|
|
223
|
+
input: JSON.stringify({ customerId: account.id }),
|
|
224
|
+
result: JSON.stringify({
|
|
225
|
+
linkState: result.linkState,
|
|
226
|
+
personId: result.personId,
|
|
227
|
+
created: result.created,
|
|
228
|
+
...result.reason ? { reason: result.reason, people: matches } : {}
|
|
229
|
+
}),
|
|
230
|
+
gate_decision: "auto",
|
|
231
|
+
outcome: "ok",
|
|
232
|
+
error: null
|
|
233
|
+
})
|
|
234
|
+
];
|
|
235
|
+
if (result.linkState === "needs_merge") {
|
|
236
|
+
const body = result.reason === "several_people" ? `${account.email} signed in to their customer account, and ${matches.length} people have this address. Merge them: the account links at the next sign-in.` : `${account.email} signed in to a new customer account, and the person with this address already has another one. Disable one account, then ask them to sign in again.`;
|
|
237
|
+
const plan = await notifyStatements(
|
|
238
|
+
db.query,
|
|
239
|
+
{
|
|
240
|
+
to: [{ role: "admin" }],
|
|
241
|
+
type: "system.message",
|
|
242
|
+
title: "A customer account needs a merge",
|
|
243
|
+
body,
|
|
244
|
+
link: matches[0] ? { kind: "record", object: "person", id: matches[0] } : null,
|
|
245
|
+
dedupeKey: `customer.needs_merge:${account.id}`,
|
|
246
|
+
source: { actor: "system" }
|
|
247
|
+
},
|
|
248
|
+
at
|
|
249
|
+
);
|
|
250
|
+
statements.push(...plan.statements);
|
|
251
|
+
}
|
|
252
|
+
await db.batch(statements);
|
|
253
|
+
return result;
|
|
254
|
+
}
|
|
255
|
+
function customerSignedInStatement(db, customerId, now) {
|
|
256
|
+
return db.updateTable("core_customer").set({ last_sign_in_at: now, updated_at: now }).where("id", "=", customerId);
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
export {
|
|
260
|
+
CUSTOMER_SIGNUP_SETTING,
|
|
261
|
+
customerSignupModeSchema,
|
|
262
|
+
loadCustomerSignup,
|
|
263
|
+
CUSTOMER_SIGNUP_SUBSCRIBERS_SETTING,
|
|
264
|
+
loadCustomerSignupSubscribers,
|
|
265
|
+
CUSTOMER_ERASE_DUE_SETTING,
|
|
266
|
+
eraseDueDaysSchema,
|
|
267
|
+
loadEraseDueDays,
|
|
268
|
+
CUSTOMER_EMAIL_CONNECTION_SETTING,
|
|
269
|
+
loadCustomerEmailConnection,
|
|
270
|
+
normaliseCustomerEmail,
|
|
271
|
+
loadCustomer,
|
|
272
|
+
loadCustomerSignIn,
|
|
273
|
+
loadCustomerByEmail,
|
|
274
|
+
customerCodeReason,
|
|
275
|
+
customerMayGetCode,
|
|
276
|
+
hasBought,
|
|
277
|
+
inviteCustomerStatement,
|
|
278
|
+
inviteCustomer,
|
|
279
|
+
CUSTOMER_LINK_AUDIT,
|
|
280
|
+
sameEmailPeople,
|
|
281
|
+
creatorFor,
|
|
282
|
+
linkCustomer,
|
|
283
|
+
customerSignedInStatement
|
|
284
|
+
};
|