direct-auth 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +486 -2
- package/dist/accounts.d.ts +118 -0
- package/dist/accounts.js +314 -0
- package/dist/apps.d.ts +85 -0
- package/dist/apps.js +449 -0
- package/dist/auth.d.ts +396 -0
- package/dist/auth.js +699 -0
- package/dist/base64.d.ts +20 -0
- package/dist/base64.js +45 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +463 -0
- package/dist/client.d.ts +170 -0
- package/dist/client.js +438 -0
- package/dist/codes.d.ts +81 -0
- package/dist/codes.js +91 -0
- package/dist/crypto.d.ts +11 -0
- package/dist/crypto.js +37 -0
- package/dist/d1.d.ts +2 -0
- package/dist/d1.js +2 -0
- package/dist/db/limits.d.ts +16 -0
- package/dist/db/limits.js +23 -0
- package/dist/db/schema.d.ts +25 -0
- package/dist/db/schema.js +136 -0
- package/dist/db/sql.d.ts +52 -0
- package/dist/db/sql.js +121 -0
- package/dist/dns.d.ts +48 -0
- package/dist/dns.js +133 -0
- package/dist/env.d.ts +39 -0
- package/dist/env.js +169 -0
- package/dist/index.d.ts +19 -0
- package/dist/index.js +14 -0
- package/dist/init.d.ts +134 -0
- package/dist/init.js +912 -0
- package/dist/jwks.d.ts +18 -0
- package/dist/jwks.js +63 -0
- package/dist/jwt.d.ts +90 -0
- package/dist/jwt.js +99 -0
- package/dist/keys.d.ts +33 -0
- package/dist/keys.js +54 -0
- package/dist/messages.d.ts +26 -0
- package/dist/messages.js +57 -0
- package/dist/migrate-cli.d.ts +82 -0
- package/dist/migrate-cli.js +564 -0
- package/dist/migrate.d.ts +99 -0
- package/dist/migrate.js +396 -0
- package/dist/node.d.ts +16 -0
- package/dist/node.js +63 -0
- package/dist/passkeys.d.ts +126 -0
- package/dist/passkeys.js +383 -0
- package/dist/passwords.d.ts +53 -0
- package/dist/passwords.js +326 -0
- package/dist/pgwire.d.ts +86 -0
- package/dist/pgwire.js +445 -0
- package/dist/phone.d.ts +11 -0
- package/dist/phone.js +18 -0
- package/dist/postgres.d.ts +2 -0
- package/dist/postgres.js +2 -0
- package/dist/providers/apple-revoke.d.ts +55 -0
- package/dist/providers/apple-revoke.js +113 -0
- package/dist/providers/apple.d.ts +28 -0
- package/dist/providers/apple.js +51 -0
- package/dist/providers/github.d.ts +28 -0
- package/dist/providers/github.js +67 -0
- package/dist/providers/google.d.ts +23 -0
- package/dist/providers/google.js +47 -0
- package/dist/providers/identity.d.ts +24 -0
- package/dist/providers/identity.js +3 -0
- package/dist/proxy.d.ts +19 -0
- package/dist/proxy.js +43 -0
- package/dist/records.d.ts +91 -0
- package/dist/records.js +264 -0
- package/dist/scrypt.d.ts +26 -0
- package/dist/scrypt.js +179 -0
- package/dist/senders/aws.d.ts +13 -0
- package/dist/senders/aws.js +47 -0
- package/dist/senders/dev.d.ts +6 -0
- package/dist/senders/dev.js +13 -0
- package/dist/senders/index.d.ts +5 -0
- package/dist/senders/index.js +4 -0
- package/dist/senders/mail.d.ts +26 -0
- package/dist/senders/mail.js +66 -0
- package/dist/senders/sms.d.ts +34 -0
- package/dist/senders/sms.js +69 -0
- package/dist/senders/smtp.d.ts +32 -0
- package/dist/senders/smtp.js +145 -0
- package/dist/senders/types.d.ts +31 -0
- package/dist/senders/types.js +25 -0
- package/dist/server.d.ts +67 -0
- package/dist/server.js +494 -0
- package/dist/sessions.d.ts +74 -0
- package/dist/sessions.js +146 -0
- package/dist/skill.d.ts +25 -0
- package/dist/skill.js +66 -0
- package/dist/sources.d.ts +138 -0
- package/dist/sources.js +931 -0
- package/dist/sqlite.d.ts +2 -0
- package/dist/sqlite.js +2 -0
- package/dist/stores/d1.d.ts +22 -0
- package/dist/stores/d1.js +23 -0
- package/dist/stores/postgres.d.ts +33 -0
- package/dist/stores/postgres.js +71 -0
- package/dist/stores/sqlite.d.ts +27 -0
- package/dist/stores/sqlite.js +55 -0
- package/dist/supabase.d.ts +71 -0
- package/dist/supabase.js +283 -0
- package/dist/tui.d.ts +178 -0
- package/dist/tui.js +537 -0
- package/package.json +90 -4
- package/skills/direct-auth/SKILL.md +101 -0
package/dist/apps.js
ADDED
|
@@ -0,0 +1,449 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `direct-auth app`: the apps under the folder it runs in, and the client added to each one checked. Its own command,
|
|
3
|
+
* not a step of `init`: init runs where the server is, and the apps are most often in folders (repositories) of their
|
|
4
|
+
* own. It needs no keys, only the server's URL (the issuer) and, for passkeys, the domain.
|
|
5
|
+
*
|
|
6
|
+
* Only what can't go wrong is done here, and only when it isn't there yet, so running it again changes nothing: the
|
|
7
|
+
* npm package added to a web app's package.json, JitPack and the dependency added to Gradle, the Swift package added
|
|
8
|
+
* to a Package.swift. The rest (the code that signs in, a pbxproj that Xcode owns, the capabilities, the files a
|
|
9
|
+
* domain serves for passkeys) comes out as steps to follow, with the URL and the domain already in them.
|
|
10
|
+
*
|
|
11
|
+
* The edits are text, not a parser: each finds the block it adds to, and when it can't tell where that is it leaves
|
|
12
|
+
* the file alone and says what to add instead.
|
|
13
|
+
*/
|
|
14
|
+
import { existsSync, mkdirSync, readFileSync, readdirSync, writeFileSync } from "node:fs";
|
|
15
|
+
import { join, relative } from "node:path";
|
|
16
|
+
import { readEnvFile, yes } from "./init.js";
|
|
17
|
+
import { offerSkill } from "./skill.js";
|
|
18
|
+
export const REPO = "https://github.com/guillecura/direct-auth";
|
|
19
|
+
export const PLACEHOLDER_URL = "https://api.example.com/auth";
|
|
20
|
+
const ARTIFACT = "com.github.guillecura:direct-auth";
|
|
21
|
+
/**
|
|
22
|
+
* The clients' version: the Android client's (clients/android/gradle.properties, what the tags follow) when it is
|
|
23
|
+
* there, this package's otherwise. One folder up from src/ and dist/ alike.
|
|
24
|
+
*/
|
|
25
|
+
export const VERSION = (() => {
|
|
26
|
+
const gradle = new URL("../clients/android/gradle.properties", import.meta.url);
|
|
27
|
+
const fromGradle = existsSync(gradle) ? /^version=(\S+)/m.exec(readFileSync(gradle, "utf8"))?.[1] : undefined;
|
|
28
|
+
return fromGradle ?? JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")).version;
|
|
29
|
+
})();
|
|
30
|
+
/** Folders no app lives in, or too big to look through: dependencies, builds, caches. */
|
|
31
|
+
const SKIP = new Set(["node_modules", "build", "dist", "out", "target", "Pods", "DerivedData", "vendor", "coverage", "bower_components"]);
|
|
32
|
+
/** Front-end frameworks, by the package that tells: the first one found names the project. */
|
|
33
|
+
const FRONTEND = [
|
|
34
|
+
"next", "nuxt", "@sveltejs/kit", "svelte", "astro", "@remix-run/react", "@angular/core", "vue", "solid-js", "preact",
|
|
35
|
+
"react", "lit", "@builder.io/qwik", "vite", "parcel", "webpack",
|
|
36
|
+
];
|
|
37
|
+
/** The apps under `root`, at most three folders down: web, Android and Apple projects, by the files they all have. */
|
|
38
|
+
export function findApps(root, depth = 3) {
|
|
39
|
+
const found = [];
|
|
40
|
+
const visit = (dir, level) => {
|
|
41
|
+
let entries;
|
|
42
|
+
try {
|
|
43
|
+
entries = readdirSync(dir, { withFileTypes: true });
|
|
44
|
+
}
|
|
45
|
+
catch {
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
48
|
+
const names = new Set(entries.map((e) => e.name));
|
|
49
|
+
const rel = relative(root, dir).split("\\").join("/") || ".";
|
|
50
|
+
const xcode = entries.find((e) => e.isDirectory() && e.name.endsWith(".xcodeproj"));
|
|
51
|
+
if (xcode)
|
|
52
|
+
found.push({ kind: "apple", dir: rel, via: xcode.name });
|
|
53
|
+
else if (names.has("Package.swift") && !ownPackage(join(dir, "Package.swift")))
|
|
54
|
+
found.push({ kind: "apple", dir: rel, via: "Package.swift" });
|
|
55
|
+
const settings = ["settings.gradle.kts", "settings.gradle"].find((n) => names.has(n));
|
|
56
|
+
if (settings && !ownGradle(join(dir, settings)))
|
|
57
|
+
found.push({ kind: "android", dir: rel, via: settings });
|
|
58
|
+
const web = webProject(dir, names);
|
|
59
|
+
if (web)
|
|
60
|
+
found.push({ kind: "web", dir: rel, via: web });
|
|
61
|
+
if (level >= depth)
|
|
62
|
+
return;
|
|
63
|
+
for (const e of entries) {
|
|
64
|
+
// A bundle (.xcodeproj, .app) is a folder too, and so is everything hidden (.git, .gradle, .next).
|
|
65
|
+
if (!e.isDirectory() || e.name.startsWith(".") || SKIP.has(e.name) || /\.(xcodeproj|xcworkspace|app|framework)$/.test(e.name))
|
|
66
|
+
continue;
|
|
67
|
+
visit(join(dir, e.name), level + 1);
|
|
68
|
+
}
|
|
69
|
+
};
|
|
70
|
+
visit(root, 0);
|
|
71
|
+
return found;
|
|
72
|
+
}
|
|
73
|
+
/** A web front end: a package.json with a framework in it (not React Native's, which is no web page). */
|
|
74
|
+
function webProject(dir, names) {
|
|
75
|
+
if (!names.has("package.json"))
|
|
76
|
+
return undefined;
|
|
77
|
+
try {
|
|
78
|
+
const pkg = JSON.parse(readFileSync(join(dir, "package.json"), "utf8"));
|
|
79
|
+
const deps = { ...pkg.dependencies, ...pkg.devDependencies };
|
|
80
|
+
if (deps["react-native"] || deps.expo)
|
|
81
|
+
return undefined;
|
|
82
|
+
const framework = FRONTEND.find((f) => deps[f]);
|
|
83
|
+
return framework ? `package.json (${framework})` : undefined;
|
|
84
|
+
}
|
|
85
|
+
catch {
|
|
86
|
+
// Not JSON: not a project this can read.
|
|
87
|
+
return undefined;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
/** This repository's own Package.swift and Gradle project: the clients themselves, not apps that use them. */
|
|
91
|
+
function ownPackage(path) {
|
|
92
|
+
return /name:\s*"DirectAuth"/.test(readFileSync(path, "utf8"));
|
|
93
|
+
}
|
|
94
|
+
function ownGradle(path) {
|
|
95
|
+
return /rootProject\.name\s*=\s*["']direct-auth["']/.test(readFileSync(path, "utf8"));
|
|
96
|
+
}
|
|
97
|
+
/** What `kind` is called on a screen. */
|
|
98
|
+
export const KIND_LABEL = { web: "Web", android: "Android", apple: "iOS, macOS" };
|
|
99
|
+
/** The client added to one app: the files changed, and the steps left. */
|
|
100
|
+
export function addToApp(app, o) {
|
|
101
|
+
const r = { changed: [], unchanged: [], steps: [] };
|
|
102
|
+
if (app.kind === "web")
|
|
103
|
+
web(app, o, r);
|
|
104
|
+
else if (app.kind === "android")
|
|
105
|
+
android(app, o, r);
|
|
106
|
+
else
|
|
107
|
+
apple(app, o, r);
|
|
108
|
+
return r;
|
|
109
|
+
}
|
|
110
|
+
const url = (o) => (o.serverUrl || PLACEHOLDER_URL).replace(/\/+$/, "");
|
|
111
|
+
const rp = (o) => o.rpId || "example.com";
|
|
112
|
+
/** Writes the file when its text is new; `edit` gets what is there (or undefined) and gives the text, or undefined to leave it. */
|
|
113
|
+
function update(o, r, path, edit) {
|
|
114
|
+
const full = join(o.root, path);
|
|
115
|
+
const before = existsSync(full) ? readFileSync(full, "utf8") : undefined;
|
|
116
|
+
const after = edit(before);
|
|
117
|
+
const shown = path.split("\\").join("/");
|
|
118
|
+
if (after === undefined || after === before) {
|
|
119
|
+
if (before !== undefined)
|
|
120
|
+
r.unchanged.push(shown);
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
mkdirSync(join(full, ".."), { recursive: true });
|
|
124
|
+
writeFileSync(full, after);
|
|
125
|
+
r.changed.push(shown);
|
|
126
|
+
}
|
|
127
|
+
// The web: the npm package, and the client from direct-auth/client.
|
|
128
|
+
/** `direct-auth` added to package.json's dependencies, in order, the file's indent kept; as it was when it has it, undefined when it isn't JSON. */
|
|
129
|
+
export function addNpmDependency(text, version) {
|
|
130
|
+
let pkg;
|
|
131
|
+
try {
|
|
132
|
+
pkg = JSON.parse(text);
|
|
133
|
+
}
|
|
134
|
+
catch {
|
|
135
|
+
return undefined;
|
|
136
|
+
}
|
|
137
|
+
const deps = (pkg.dependencies ?? {});
|
|
138
|
+
const dev = (pkg.devDependencies ?? {});
|
|
139
|
+
if (deps["direct-auth"] || dev["direct-auth"])
|
|
140
|
+
return text;
|
|
141
|
+
const all = { ...deps, "direct-auth": `^${version}` };
|
|
142
|
+
pkg.dependencies = Object.fromEntries(Object.keys(all).sort().map((k) => [k, all[k]]));
|
|
143
|
+
const indent = /^([ \t]+)"/m.exec(text)?.[1] ?? " ";
|
|
144
|
+
return `${JSON.stringify(pkg, null, indent)}\n`;
|
|
145
|
+
}
|
|
146
|
+
/** The install command of the package manager the app's lockfile names. */
|
|
147
|
+
function installCommand(dir) {
|
|
148
|
+
if (existsSync(join(dir, "pnpm-lock.yaml")))
|
|
149
|
+
return "pnpm install";
|
|
150
|
+
if (existsSync(join(dir, "yarn.lock")))
|
|
151
|
+
return "yarn install";
|
|
152
|
+
if (existsSync(join(dir, "bun.lock")) || existsSync(join(dir, "bun.lockb")))
|
|
153
|
+
return "bun install";
|
|
154
|
+
return "npm install";
|
|
155
|
+
}
|
|
156
|
+
function web(app, o, r) {
|
|
157
|
+
let added = true;
|
|
158
|
+
update(o, r, join(app.dir, "package.json"), (text) => {
|
|
159
|
+
if (text === undefined)
|
|
160
|
+
return undefined;
|
|
161
|
+
const next = addNpmDependency(text, o.version);
|
|
162
|
+
added = next !== undefined;
|
|
163
|
+
return next;
|
|
164
|
+
});
|
|
165
|
+
if (!added)
|
|
166
|
+
r.steps.push(`Add to package.json's dependencies: "direct-auth": "^${o.version}"`);
|
|
167
|
+
r.steps.push(`${installCommand(join(o.root, app.dir))}${app.dir === "." ? "" : ` (in ${app.dir})`}`, "One for the page:", ` import { createAuthClient } from "direct-auth/client";`, ` const auth = createAuthClient({ url: "${url(o)}" });`, "Whatever calls your API: await auth.accessToken()", "A page on another site than the server's: add its origin to the server's DIRECT_AUTH_ORIGINS.", `Passkeys: the page's origin (https://${rp(o)}) in the server's PASSKEY_ORIGINS.`);
|
|
168
|
+
}
|
|
169
|
+
// Android: JitPack, the dependency, and the client.
|
|
170
|
+
function android(app, o, r) {
|
|
171
|
+
const tag = `v${o.version}`;
|
|
172
|
+
const settings = join(app.dir, app.via);
|
|
173
|
+
const kts = app.via.endsWith(".kts");
|
|
174
|
+
const settingsText = readFileSync(join(o.root, settings), "utf8");
|
|
175
|
+
// JitPack: in settings' dependencyResolutionManagement, or an older build's allprojects in the root build file.
|
|
176
|
+
const rootBuild = join(app.dir, kts ? "build.gradle.kts" : "build.gradle");
|
|
177
|
+
const repoIn = /dependencyResolutionManagement\s*\{/.test(settingsText) || !existsSync(join(o.root, rootBuild)) ? settings : rootBuild;
|
|
178
|
+
let added = true;
|
|
179
|
+
update(o, r, repoIn, (text) => {
|
|
180
|
+
if (text === undefined)
|
|
181
|
+
return undefined;
|
|
182
|
+
const next = addJitpack(text, repoIn.endsWith(".kts"));
|
|
183
|
+
added = next !== undefined;
|
|
184
|
+
return next ?? undefined;
|
|
185
|
+
});
|
|
186
|
+
if (!added)
|
|
187
|
+
r.steps.push(`Add JitPack to the repositories in ${repoIn.split("\\").join("/")}: ${kts ? 'maven("https://jitpack.io")' : "maven { url = 'https://jitpack.io' }"}`);
|
|
188
|
+
// The dependency: in the version catalog when there is one, and the app module's build file.
|
|
189
|
+
const module = appModule(o.root, app.dir, settingsText);
|
|
190
|
+
const catalog = join(app.dir, "gradle", "libs.versions.toml");
|
|
191
|
+
let notation = kts ? `implementation("${ARTIFACT}:${tag}")` : `implementation '${ARTIFACT}:${tag}'`;
|
|
192
|
+
if (existsSync(join(o.root, catalog))) {
|
|
193
|
+
let alias = "direct-auth";
|
|
194
|
+
update(o, r, catalog, (text) => {
|
|
195
|
+
const had = text && catalogAlias(text);
|
|
196
|
+
if (had)
|
|
197
|
+
alias = had;
|
|
198
|
+
return text === undefined || had ? undefined : addToCatalog(text, tag);
|
|
199
|
+
});
|
|
200
|
+
const accessor = `libs.${alias.replace(/[-_]/g, ".")}`;
|
|
201
|
+
notation = kts ? `implementation(${accessor})` : `implementation ${accessor}`;
|
|
202
|
+
}
|
|
203
|
+
if (module) {
|
|
204
|
+
update(o, r, module, (text) => (text === undefined ? undefined : addGradleDependency(text, notation)));
|
|
205
|
+
}
|
|
206
|
+
else
|
|
207
|
+
r.steps.push(`Add to the app module's dependencies: ${notation}`);
|
|
208
|
+
r.steps.push("One for the app, in Application.onCreate or a singleton:", ` val auth = DirectAuth(applicationContext, "${url(o)}")`, "Google, from an activity (the web client's ID, which the server lists in GOOGLE_CLIENT_IDS):", ` auth.signInWithGoogle(activity, webClientId = "WEB_CLIENT_ID.apps.googleusercontent.com")`, `Passkeys: https://${rp(o)}/.well-known/assetlinks.json names the app's package and its signing certificate's SHA-256, with delegate_permission/common.get_login_creds.`, "And the server's PASSKEY_ORIGINS gets android:apk-key-hash:<that SHA-256, base64url>.");
|
|
209
|
+
}
|
|
210
|
+
/** The app module's build file, relative to root: the included module that applies the Android application plugin. */
|
|
211
|
+
function appModule(root, dir, settings) {
|
|
212
|
+
const included = [...settings.matchAll(/^\s*include\b(.*)$/gm)].flatMap((m) => [...m[1].matchAll(/["']:?([\w:.-]+)["']/g)].map((x) => x[1].replace(/:/g, "/")));
|
|
213
|
+
for (const name of new Set([...included, "app"])) {
|
|
214
|
+
for (const file of ["build.gradle.kts", "build.gradle"]) {
|
|
215
|
+
const path = join(dir, name, file);
|
|
216
|
+
if (existsSync(join(root, path)) && /com\.android\.application|android\.application/.test(readFileSync(join(root, path), "utf8")))
|
|
217
|
+
return path;
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
return undefined;
|
|
221
|
+
}
|
|
222
|
+
/** JitPack added to the repositories block; undefined when there is none this can find, the text as it was when it has it. */
|
|
223
|
+
export function addJitpack(text, kts) {
|
|
224
|
+
if (text.includes("jitpack.io"))
|
|
225
|
+
return text;
|
|
226
|
+
const outer = /dependencyResolutionManagement\s*\{/.exec(text) ?? /allprojects\s*\{/.exec(text);
|
|
227
|
+
if (!outer)
|
|
228
|
+
return undefined;
|
|
229
|
+
const block = /repositories\s*\{/g;
|
|
230
|
+
block.lastIndex = outer.index;
|
|
231
|
+
const repos = block.exec(text);
|
|
232
|
+
if (!repos)
|
|
233
|
+
return undefined;
|
|
234
|
+
const close = closing(text, repos.index + repos[0].length - 1);
|
|
235
|
+
if (close < 0)
|
|
236
|
+
return undefined;
|
|
237
|
+
return insertLine(text, close, kts ? 'maven("https://jitpack.io")' : "maven { url = 'https://jitpack.io' }");
|
|
238
|
+
}
|
|
239
|
+
/** The dependency added at the end of the top-level dependencies block (one made when there is none); as it was when it has it. */
|
|
240
|
+
export function addGradleDependency(text, notation) {
|
|
241
|
+
const what = /libs\.[\w.]+/.exec(notation)?.[0] ?? ARTIFACT;
|
|
242
|
+
if (text.includes(ARTIFACT) || text.includes(what))
|
|
243
|
+
return text;
|
|
244
|
+
const deps = /^dependencies\s*\{/m.exec(text);
|
|
245
|
+
const close = deps ? closing(text, deps.index + deps[0].length - 1) : -1;
|
|
246
|
+
if (close < 0)
|
|
247
|
+
return `${text.replace(/\n*$/, "\n")}\ndependencies {\n ${notation}\n}\n`;
|
|
248
|
+
return insertLine(text, close, notation);
|
|
249
|
+
}
|
|
250
|
+
/** The catalog's alias for direct-auth, when it has one. */
|
|
251
|
+
export function catalogAlias(toml) {
|
|
252
|
+
return /^\s*([\w-]+)\s*=.*com\.github\.guillecura:direct-auth/m.exec(toml)?.[1] ?? /^\s*([\w-]+)\s*=.*group\s*=\s*"com\.github\.guillecura",\s*name\s*=\s*"direct-auth"/m.exec(toml)?.[1];
|
|
253
|
+
}
|
|
254
|
+
/** `direct-auth` added to the version catalog: its version under [versions], the library under [libraries]. */
|
|
255
|
+
export function addToCatalog(toml, tag) {
|
|
256
|
+
if (catalogAlias(toml))
|
|
257
|
+
return toml;
|
|
258
|
+
let text = toml;
|
|
259
|
+
const hasVersions = /^\[versions\]\s*$/m.test(text);
|
|
260
|
+
if (hasVersions)
|
|
261
|
+
text = appendToSection(text, "versions", `direct-auth = "${tag}"`);
|
|
262
|
+
const library = hasVersions
|
|
263
|
+
? `direct-auth = { group = "com.github.guillecura", name = "direct-auth", version.ref = "direct-auth" }`
|
|
264
|
+
: `direct-auth = { module = "${ARTIFACT}", version = "${tag}" }`;
|
|
265
|
+
if (/^\[libraries\]\s*$/m.test(text))
|
|
266
|
+
return appendToSection(text, "libraries", library);
|
|
267
|
+
return `${text.replace(/\n*$/, "\n")}\n[libraries]\n${library}\n`;
|
|
268
|
+
}
|
|
269
|
+
/** A line after the last one of a TOML section (before the blank lines that end it). */
|
|
270
|
+
function appendToSection(text, section, line) {
|
|
271
|
+
const lines = text.split("\n");
|
|
272
|
+
const start = lines.findIndex((l) => l.trim() === `[${section}]`);
|
|
273
|
+
let end = lines.findIndex((l, i) => i > start && /^\s*\[/.test(l));
|
|
274
|
+
if (end < 0)
|
|
275
|
+
end = lines.length;
|
|
276
|
+
let last = end - 1;
|
|
277
|
+
while (last > start && lines[last].trim() === "")
|
|
278
|
+
last -= 1;
|
|
279
|
+
lines.splice(last + 1, 0, line);
|
|
280
|
+
return lines.join("\n");
|
|
281
|
+
}
|
|
282
|
+
/** The index of the brace that closes the one at `open`; -1 when it never does. Strings and comments aren't told apart: Gradle files rarely need it. */
|
|
283
|
+
function closing(text, open) {
|
|
284
|
+
let depth = 0;
|
|
285
|
+
for (let i = open; i < text.length; i += 1) {
|
|
286
|
+
if (text[i] === "{")
|
|
287
|
+
depth += 1;
|
|
288
|
+
else if (text[i] === "}" && --depth === 0)
|
|
289
|
+
return i;
|
|
290
|
+
}
|
|
291
|
+
return -1;
|
|
292
|
+
}
|
|
293
|
+
/**
|
|
294
|
+
* A line inserted before the brace or bracket at `close`, indented as the block's last line, or one step in from the
|
|
295
|
+
* brace. A block closed on its own line (`{ google() }`) gets the line before the brace, after a `; `.
|
|
296
|
+
*/
|
|
297
|
+
function insertLine(text, close, line, comma = false) {
|
|
298
|
+
const lineStart = text.lastIndexOf("\n", close - 1) + 1;
|
|
299
|
+
const before = text.slice(lineStart, close);
|
|
300
|
+
if (before.trim() !== "")
|
|
301
|
+
return `${text.slice(0, close).trimEnd()}${comma ? ", " : "; "}${line} ${text.slice(close)}`;
|
|
302
|
+
const braceIndent = before;
|
|
303
|
+
const prev = text.slice(0, lineStart).replace(/\n\s*$/, "");
|
|
304
|
+
const prevLine = prev.slice(prev.lastIndexOf("\n") + 1);
|
|
305
|
+
const indent = /[{[(]\s*$/.test(prevLine) ? `${braceIndent} ` : (/^\s*/.exec(prevLine)?.[0] ?? `${braceIndent} `);
|
|
306
|
+
const head = comma && !/[,[(]\s*$/.test(prev) ? `${prev},` : prev;
|
|
307
|
+
return `${head}\n${indent}${line}${comma ? "," : ""}\n${text.slice(lineStart)}`;
|
|
308
|
+
}
|
|
309
|
+
// Apple: the package in Package.swift; an Xcode project's steps.
|
|
310
|
+
function apple(app, o, r) {
|
|
311
|
+
if (app.via === "Package.swift") {
|
|
312
|
+
let added = true;
|
|
313
|
+
update(o, r, join(app.dir, "Package.swift"), (text) => {
|
|
314
|
+
if (text === undefined)
|
|
315
|
+
return undefined;
|
|
316
|
+
const next = addSwiftPackage(text, o.version);
|
|
317
|
+
added = next !== undefined;
|
|
318
|
+
return next;
|
|
319
|
+
});
|
|
320
|
+
if (!added)
|
|
321
|
+
r.steps.push(`Add to Package.swift's dependencies: ${swiftPackage(o.version)}`);
|
|
322
|
+
r.steps.push(`And to the app target's dependencies: .product(name: "DirectAuth", package: "direct-auth")`);
|
|
323
|
+
}
|
|
324
|
+
else {
|
|
325
|
+
r.steps.push(`Xcode › File › Add Package Dependencies… › ${REPO} (the DirectAuth library)`);
|
|
326
|
+
}
|
|
327
|
+
r.steps.push("The target's Signing & Capabilities › + Capability › Sign in with Apple", `Passkeys: + Capability › Associated Domains › webcredentials:${rp(o)}`, `And https://${rp(o)}/.well-known/apple-app-site-association lists TEAMID.your.bundle.id under webcredentials.apps.`, "One for the app:", ` let auth = DirectAuth(url: URL(string: "${url(o)}")!)`, "Signing in, from a button:", " try await auth.signInWithApple(presentationAnchor: window)", "Whatever calls your API: try await auth.accessToken()");
|
|
328
|
+
}
|
|
329
|
+
/** The leading whitespace of the line `at` is on. */
|
|
330
|
+
const lineIndent = (text, at) => /^[ \t]*/.exec(text.slice(text.lastIndexOf("\n", at - 1) + 1))[0];
|
|
331
|
+
const swiftPackage = (version) => `.package(url: "${REPO}", from: "${version}")`;
|
|
332
|
+
/**
|
|
333
|
+
* The package added to Package(…)'s own `dependencies:` (not a target's), made before `targets:` when there is none;
|
|
334
|
+
* as it was when it has it; undefined when Package( can't be found.
|
|
335
|
+
*/
|
|
336
|
+
export function addSwiftPackage(text, version) {
|
|
337
|
+
if (text.includes("guillecura/direct-auth"))
|
|
338
|
+
return text;
|
|
339
|
+
const start = /\bPackage\s*\(/.exec(text);
|
|
340
|
+
if (!start)
|
|
341
|
+
return undefined;
|
|
342
|
+
// The arguments at Package('s own depth: a target's dependencies are deeper.
|
|
343
|
+
let depth = 0;
|
|
344
|
+
let deps = -1;
|
|
345
|
+
let targets = -1;
|
|
346
|
+
for (let i = start.index + start[0].length - 1; i < text.length; i += 1) {
|
|
347
|
+
const c = text[i];
|
|
348
|
+
if (c === "(" || c === "[" || c === "{")
|
|
349
|
+
depth += 1;
|
|
350
|
+
else if (c === ")" || c === "]" || c === "}") {
|
|
351
|
+
if (--depth === 0)
|
|
352
|
+
break;
|
|
353
|
+
}
|
|
354
|
+
else if (depth === 1 && deps < 0 && text.startsWith("dependencies:", i) && !/\w/.test(text[i - 1]))
|
|
355
|
+
deps = i;
|
|
356
|
+
else if (depth === 1 && targets < 0 && text.startsWith("targets:", i) && !/\w/.test(text[i - 1]))
|
|
357
|
+
targets = i;
|
|
358
|
+
}
|
|
359
|
+
const line = swiftPackage(version);
|
|
360
|
+
if (deps >= 0) {
|
|
361
|
+
const open = text.indexOf("[", deps);
|
|
362
|
+
let d = 0;
|
|
363
|
+
let close = -1;
|
|
364
|
+
for (let i = open; i < text.length; i += 1) {
|
|
365
|
+
if (text[i] === "[" || text[i] === "(")
|
|
366
|
+
d += 1;
|
|
367
|
+
else if ((text[i] === "]" || text[i] === ")") && --d === 0) {
|
|
368
|
+
close = i;
|
|
369
|
+
break;
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
if (close < 0)
|
|
373
|
+
return undefined;
|
|
374
|
+
if (text.slice(open + 1, close).trim() === "") {
|
|
375
|
+
const indent = lineIndent(text, deps);
|
|
376
|
+
return `${text.slice(0, open)}[\n${indent} ${line},\n${indent}]${text.slice(close + 1)}`;
|
|
377
|
+
}
|
|
378
|
+
return insertLine(text, close, line, true);
|
|
379
|
+
}
|
|
380
|
+
if (targets < 0)
|
|
381
|
+
return undefined;
|
|
382
|
+
const indent = lineIndent(text, targets);
|
|
383
|
+
return `${text.slice(0, targets)}dependencies: [\n${indent} ${line},\n${indent}],\n${indent}${text.slice(targets)}`;
|
|
384
|
+
}
|
|
385
|
+
export async function app(io, o) {
|
|
386
|
+
const found = findApps(o.cwd);
|
|
387
|
+
if (!found.length) {
|
|
388
|
+
io.say("No app found here: a web project (package.json with a front-end framework), Android (settings.gradle) or iOS and macOS (an .xcodeproj, Package.swift), up to three folders down.", "note");
|
|
389
|
+
io.say("Run it in the app's folder; README › Connect an app has the rest.");
|
|
390
|
+
return 1;
|
|
391
|
+
}
|
|
392
|
+
let apps;
|
|
393
|
+
if (io.apps)
|
|
394
|
+
apps = await io.apps(found);
|
|
395
|
+
else {
|
|
396
|
+
apps = [];
|
|
397
|
+
io.say("");
|
|
398
|
+
for (const a of found)
|
|
399
|
+
if (await yes(io, `Add direct-auth to ${KIND_LABEL[a.kind]} in ${a.dir === "." ? "./" : a.dir} (${a.via})?`, true))
|
|
400
|
+
apps.push(a);
|
|
401
|
+
}
|
|
402
|
+
if (!apps.length) {
|
|
403
|
+
io.say("No app chosen: nothing changed.");
|
|
404
|
+
return 0;
|
|
405
|
+
}
|
|
406
|
+
io.chosen?.(apps);
|
|
407
|
+
const file = o.envFile ?? ".env";
|
|
408
|
+
const env = readEnvFile(join(o.cwd, file));
|
|
409
|
+
let serverUrl = o.url?.replace(/\/+$/, "");
|
|
410
|
+
if (!serverUrl && env.DIRECT_AUTH_ISSUER) {
|
|
411
|
+
serverUrl = env.DIRECT_AUTH_ISSUER.replace(/\/+$/, "");
|
|
412
|
+
io.say(` The server's URL from ${file}: ${serverUrl}`, "ok");
|
|
413
|
+
}
|
|
414
|
+
serverUrl ??= await optional(io, `Your server's URL, the issuer, e.g. ${PLACEHOLDER_URL} (optional)`, (v) => /^https?:\/\/[^\s/]+/.test(v) ? undefined : "an http(s) address, like https://api.example.com/auth");
|
|
415
|
+
for (const a of apps) {
|
|
416
|
+
io.section?.(a);
|
|
417
|
+
io.say("");
|
|
418
|
+
io.say(`${KIND_LABEL[a.kind]} in ${a.dir === "." ? "./" : a.dir}`);
|
|
419
|
+
const r = addToApp(a, { root: o.cwd, version: o.version ?? VERSION, serverUrl, rpId: env.PASSKEY_RP_ID });
|
|
420
|
+
for (const path of r.changed)
|
|
421
|
+
io.say(` ✓ ${path}`, "ok");
|
|
422
|
+
for (const path of r.unchanged)
|
|
423
|
+
io.say(` ✓ ${path} (already there)`, "dim");
|
|
424
|
+
// Steps numbered, the code under each indented and set apart: what to do reads down the left edge.
|
|
425
|
+
let n = 0;
|
|
426
|
+
for (const step of r.steps) {
|
|
427
|
+
if (!step)
|
|
428
|
+
continue;
|
|
429
|
+
if (step.startsWith(" "))
|
|
430
|
+
io.say(` ${step.slice(2)}`, "code");
|
|
431
|
+
else
|
|
432
|
+
io.say(` ${++n}. ${step}`);
|
|
433
|
+
}
|
|
434
|
+
}
|
|
435
|
+
await offerSkill(io, { cwd: o.cwd });
|
|
436
|
+
return 0;
|
|
437
|
+
}
|
|
438
|
+
/** Asked until it is empty or right; empty is undefined. */
|
|
439
|
+
async function optional(io, question, wrong) {
|
|
440
|
+
for (;;) {
|
|
441
|
+
const v = (await io.ask(` ${question}: `)).trim().replace(/\/+$/, "");
|
|
442
|
+
if (!v)
|
|
443
|
+
return undefined;
|
|
444
|
+
const why = wrong(v);
|
|
445
|
+
if (!why)
|
|
446
|
+
return v;
|
|
447
|
+
io.say(` ${why}.`, "bad");
|
|
448
|
+
}
|
|
449
|
+
}
|