@quatronic/sdk 0.10.1-rc.1 → 0.10.1-test.97e91bf
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 +6 -0
- package/dist/chunk-JM5LHJUJ.js +32 -0
- package/dist/chunk-JM5LHJUJ.js.map +1 -0
- package/dist/{chunk-YFZB5EW6.js → chunk-P5GBQVO7.js} +2 -2
- package/dist/{chunk-IFESUTF2.js → chunk-VQKYPW5V.js} +7 -3
- package/dist/chunk-VQKYPW5V.js.map +1 -0
- package/dist/{chunk-POZI4OKJ.js → chunk-WOFBDOMY.js} +2 -2
- package/dist/{chunk-TPBRMW5N.js → chunk-YCKDMG4B.js} +30 -1
- package/dist/chunk-YCKDMG4B.js.map +1 -0
- package/dist/chunk-YJZZURE4.js +83 -0
- package/dist/chunk-YJZZURE4.js.map +1 -0
- package/dist/cli/skills-postinstall.js +13 -6
- package/dist/cli/skills.js +11 -5
- package/dist/context-CWvUIBHJ.d.ts +196 -0
- package/dist/eslint/index.d.ts +11 -1
- package/dist/eslint/index.js +123 -4
- package/dist/eslint/index.js.map +1 -1
- package/dist/expo/auth/index.d.ts +14 -0
- package/dist/expo/auth/index.js +324 -0
- package/dist/expo/auth/index.js.map +1 -0
- package/dist/expo/config/index.d.ts +38 -0
- package/dist/expo/config/index.js +35 -0
- package/dist/expo/config/index.js.map +1 -0
- package/dist/expo/log/index.d.ts +9 -0
- package/dist/expo/log/index.js +16 -0
- package/dist/expo/log/index.js.map +1 -0
- package/dist/expo/query/index.d.ts +41 -0
- package/dist/expo/query/index.js +98 -0
- package/dist/expo/query/index.js.map +1 -0
- package/dist/expo/sentry/index.d.ts +33 -0
- package/dist/expo/sentry/index.js +100 -0
- package/dist/expo/sentry/index.js.map +1 -0
- package/dist/expo/testing/index.d.ts +32 -0
- package/dist/expo/testing/index.js +58 -0
- package/dist/expo/testing/index.js.map +1 -0
- package/dist/next/auth/index.d.ts +50 -0
- package/dist/next/auth/index.js +523 -101
- package/dist/next/auth/index.js.map +1 -1
- package/dist/next/boot/index.js +3 -3
- package/dist/next/db/index.js +1 -1
- package/dist/next/security/index.d.ts +24 -1
- package/dist/next/security/index.js +29 -0
- package/dist/next/security/index.js.map +1 -1
- package/dist/next/sentry/client.js +3 -3
- package/dist/next/sentry/client.js.map +1 -1
- package/dist/next/sentry/index.js +1 -1
- package/dist/next/sentry/register.js +3 -3
- package/dist/node/sentry/index.js +1 -1
- package/dist/node/sentry/register.js +2 -2
- package/package.json +75 -2
- package/skills/catalog.json +3 -0
- package/skills/qore-add-api-route/SKILL.md +1 -1
- package/skills/qore-add-connection/SKILL.next.md +3 -1
- package/skills/qore-add-connection/SKILL.node.md +3 -1
- package/skills/qore-add-env-key/SKILL.md +174 -9
- package/skills/qore-add-feature/SKILL.md +1 -1
- package/skills/qore-add-integration/SKILL.next.md +4 -2
- package/skills/qore-add-integration/SKILL.node.md +6 -6
- package/skills/qore-add-page/SKILL.md +1 -1
- package/skills/qore-author-skill/SKILL.md +1 -1
- package/skills/qore-debug-issue/SKILL.md +10 -0
- package/skills/qore-mobile-add-screen/SKILL.md +64 -0
- package/skills/qore-mobile-call-server/SKILL.md +75 -0
- package/skills/qore-mobile-run-on-device/SKILL.md +44 -0
- package/skills/qore-observability/SKILL.md +17 -0
- package/skills/qore-secure-io/SKILL.md +15 -0
- package/skills/qore-ship-checklist/SKILL.md +10 -0
- package/skills/qore-translate-strings/SKILL.md +10 -0
- package/skills/qore-use-addons/SKILL.md +2 -0
- package/skills/qore-use-database/SKILL.md +2 -0
- package/skills/qore-use-design-system/SKILL.md +1 -1
- package/skills/qore-use-mail-domain/SKILL.next.md +1 -1
- package/skills/qore-use-mail-domain/SKILL.node.md +2 -2
- package/skills/qore-use-permissions/SKILL.md +10 -0
- package/dist/chunk-IFESUTF2.js.map +0 -1
- package/dist/chunk-TPBRMW5N.js.map +0 -1
- /package/dist/{chunk-YFZB5EW6.js.map → chunk-P5GBQVO7.js.map} +0 -0
- /package/dist/{chunk-POZI4OKJ.js.map → chunk-WOFBDOMY.js.map} +0 -0
package/README.md
CHANGED
|
@@ -23,6 +23,12 @@ app runs against its own proxy, and `@quatronic/sdk/eslint` for the fourteen
|
|
|
23
23
|
`qdc/*` lint rules —
|
|
24
24
|
[`docs/security-rules.md`](docs/security-rules.md).
|
|
25
25
|
|
|
26
|
+
## Web and mobile
|
|
27
|
+
|
|
28
|
+
A module can carry a phone app (`mobile/`, Expo) beside its Next app. Which
|
|
29
|
+
entry runs where, what it may import and its counterpart on the other side:
|
|
30
|
+
[`docs/surfaces.md`](docs/surfaces.md).
|
|
31
|
+
|
|
26
32
|
## Claude Code skills
|
|
27
33
|
|
|
28
34
|
The SDK ships the app's managed Claude Code skills (`skills/`, one entry per
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
// src/expo/core/errors.ts
|
|
2
|
+
var Unauthenticated = class extends Error {
|
|
3
|
+
constructor() {
|
|
4
|
+
super("unauthenticated");
|
|
5
|
+
this.name = "Unauthenticated";
|
|
6
|
+
}
|
|
7
|
+
};
|
|
8
|
+
var UpgradeRequired = class extends Error {
|
|
9
|
+
constructor(minApiLevel) {
|
|
10
|
+
super("upgrade_required");
|
|
11
|
+
this.minApiLevel = minApiLevel;
|
|
12
|
+
this.name = "UpgradeRequired";
|
|
13
|
+
}
|
|
14
|
+
minApiLevel;
|
|
15
|
+
};
|
|
16
|
+
var ApiError = class extends Error {
|
|
17
|
+
constructor(status, code) {
|
|
18
|
+
super(code ?? `http_${status}`);
|
|
19
|
+
this.status = status;
|
|
20
|
+
this.code = code;
|
|
21
|
+
this.name = "ApiError";
|
|
22
|
+
}
|
|
23
|
+
status;
|
|
24
|
+
code;
|
|
25
|
+
};
|
|
26
|
+
|
|
27
|
+
export {
|
|
28
|
+
Unauthenticated,
|
|
29
|
+
UpgradeRequired,
|
|
30
|
+
ApiError
|
|
31
|
+
};
|
|
32
|
+
//# sourceMappingURL=chunk-JM5LHJUJ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/expo/core/errors.ts"],"sourcesContent":["/** The app holds no session, or the server no longer accepts it. Show the login screen. */\nexport class Unauthenticated extends Error {\n constructor() {\n super(\"unauthenticated\")\n this.name = \"Unauthenticated\"\n }\n}\n\n/**\n * The server no longer serves this build's API level (HTTP 426). Show the\n * upgrade screen; retrying cannot succeed. `minApiLevel` is what the server\n * asks for, when it said.\n */\nexport class UpgradeRequired extends Error {\n constructor(readonly minApiLevel: number | null) {\n super(\"upgrade_required\")\n this.name = \"UpgradeRequired\"\n }\n}\n\n/** The app's server answered with an error status. `code` is its `{ error }` field, when it sent one. */\nexport class ApiError extends Error {\n constructor(\n readonly status: number,\n readonly code: string | null,\n ) {\n super(code ?? `http_${status}`)\n this.name = \"ApiError\"\n }\n}\n"],"mappings":";AACO,IAAM,kBAAN,cAA8B,MAAM;AAAA,EACzC,cAAc;AACZ,UAAM,iBAAiB;AACvB,SAAK,OAAO;AAAA,EACd;AACF;AAOO,IAAM,kBAAN,cAA8B,MAAM;AAAA,EACzC,YAAqB,aAA4B;AAC/C,UAAM,kBAAkB;AADL;AAEnB,SAAK,OAAO;AAAA,EACd;AAAA,EAHqB;AAIvB;AAGO,IAAM,WAAN,cAAuB,MAAM;AAAA,EAClC,YACW,QACA,MACT;AACA,UAAM,QAAQ,QAAQ,MAAM,EAAE;AAHrB;AACA;AAGT,SAAK,OAAO;AAAA,EACd;AAAA,EALW;AAAA,EACA;AAKb;","names":[]}
|
|
@@ -9,7 +9,7 @@ import {
|
|
|
9
9
|
scrubEvent,
|
|
10
10
|
scrubLog,
|
|
11
11
|
scrubSpan
|
|
12
|
-
} from "./chunk-
|
|
12
|
+
} from "./chunk-VQKYPW5V.js";
|
|
13
13
|
|
|
14
14
|
// src/sentry-core/noise.ts
|
|
15
15
|
var NOISE_EXACT = /* @__PURE__ */ new Set(["/favicon.ico", "/api/auth/me"]);
|
|
@@ -104,4 +104,4 @@ function initSentry(sentry, runtime, cfg, extra = {}) {
|
|
|
104
104
|
export {
|
|
105
105
|
initSentry
|
|
106
106
|
};
|
|
107
|
-
//# sourceMappingURL=chunk-
|
|
107
|
+
//# sourceMappingURL=chunk-P5GBQVO7.js.map
|
|
@@ -5,7 +5,8 @@ var URL_USERINFO = /\b([a-z][a-z0-9+.-]{0,31}:\/\/)[^/\s:@]+(?::[^/\s@]*)?@/gi;
|
|
|
5
5
|
var JWT = /eyJ[\w-]+\.[\w-]+\.[\w-]+/g;
|
|
6
6
|
var AUTH_SCHEME = /\b(Bearer|Basic)\s+\S+/gi;
|
|
7
7
|
var PARAMS_TAIL = /\bparams:\s.*$/s;
|
|
8
|
-
var
|
|
8
|
+
var TEXT_QUERY_PARAM = /([?&])([A-Za-z_]{1,32})=([^&\s#"']+)/g;
|
|
9
|
+
var SECRET_PARAMS = /* @__PURE__ */ new Set(["token", "code", "state", "password", "secret", "key", "session", "access_token", "refresh_token", "id_token", "verifier", "code_verifier"]);
|
|
9
10
|
var SECRET_HEADERS = /* @__PURE__ */ new Set([
|
|
10
11
|
"authorization",
|
|
11
12
|
"cookie",
|
|
@@ -36,7 +37,10 @@ function maskSecretValues(s) {
|
|
|
36
37
|
return secretState().longestFirst.reduce((acc, v) => acc.replaceAll(v, REDACTED), s);
|
|
37
38
|
}
|
|
38
39
|
function redactText(s) {
|
|
39
|
-
return maskSecretValues(s).replace(URL_USERINFO, `$1${REDACTED}@`).replace(PARAMS_TAIL, "params: [redacted]").replace(
|
|
40
|
+
return maskSecretValues(s).replace(URL_USERINFO, `$1${REDACTED}@`).replace(PARAMS_TAIL, "params: [redacted]").replace(
|
|
41
|
+
TEXT_QUERY_PARAM,
|
|
42
|
+
(m, sep, k) => SECRET_PARAMS.has(k.toLowerCase()) ? `${sep}${k}=[redacted]` : m
|
|
43
|
+
).replace(AUTH_SCHEME, "$1 [redacted]").replace(JWT, "[jwt]").replace(EMAIL, "[email]");
|
|
40
44
|
}
|
|
41
45
|
function redactQuery(query) {
|
|
42
46
|
return query.split("&").map((pair) => {
|
|
@@ -108,4 +112,4 @@ export {
|
|
|
108
112
|
scrubLog,
|
|
109
113
|
scrubSpan
|
|
110
114
|
};
|
|
111
|
-
//# sourceMappingURL=chunk-
|
|
115
|
+
//# sourceMappingURL=chunk-VQKYPW5V.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/sentry-core/scrub.ts"],"sourcesContent":["export const REDACTED = \"●●●\"\n\n// Bounded and anchored (`(?<![...])` + `{1,64}` local part, no `.` in the\n// domain-char class) so it cannot backtrack catastrophically on long runs of\n// email-charset bytes — see the fix-round-1 report for the O(n²) it replaced.\nconst EMAIL = /(?<![A-Z0-9._%+-])[A-Z0-9._%+-]{1,64}@[A-Z0-9-]+(?:\\.[A-Z0-9-]+)*\\.[A-Z]{2,}/gi\nconst URL_USERINFO = /\\b([a-z][a-z0-9+.-]{0,31}:\\/\\/)[^/\\s:@]+(?::[^/\\s@]*)?@/gi\nconst JWT = /eyJ[\\w-]+\\.[\\w-]+\\.[\\w-]+/g\nconst AUTH_SCHEME = /\\b(Bearer|Basic)\\s+\\S+/gi\nconst PARAMS_TAIL = /\\bparams:\\s.*$/s\n// A secret query parameter inside free text: a logged redirect such as\n// `acme-shop://auth/return?code=…` carries the one-time mobile handoff code.\nconst TEXT_QUERY_PARAM = /([?&])([A-Za-z_]{1,32})=([^&\\s#\"']+)/g\nexport const SECRET_PARAMS: ReadonlySet<string> = new Set([\"token\", \"code\", \"state\", \"password\", \"secret\", \"key\", \"session\", \"access_token\", \"refresh_token\", \"id_token\", \"verifier\", \"code_verifier\"])\nconst SECRET_HEADERS = new Set([\n \"authorization\",\n \"cookie\",\n \"set-cookie\",\n \"x-qdc-connection-token\",\n \"x-forwarded-for\",\n \"x-real-ip\",\n \"forwarded\",\n \"user-agent\",\n])\nconst DROP_LOG_ATTRS = new Set([\"ip\", \"ip_address\", \"user_agent\", \"email\", \"user_email\", \"server.address\"])\nconst REDACT_KEYS = new Set([\"db.connection_string\", \"db.user\"])\nconst REDACT_PREFIXES = [\"net.peer.\", \"net.sock.\", \"net.host.\", \"network.peer.\", \"network.local.\"]\nconst DROP_SPAN_KEYS = new Set([\"user_agent.original\", \"http.user_agent\", \"client.address\", \"http.client_ip\"])\nconst DROP_SPAN_PREFIXES = [\"http.request.header.\", \"http.response.header.\"]\nconst URL_SPAN_KEYS = new Set([\"url.full\", \"http.url\", \"url\", \"http.target\", \"url.query\", \"http.query\"])\n\nconst SECRETS = Symbol.for(\"@quatronic/sdk.sentry-secret-values\")\ntype SecretHolder = { [SECRETS]?: { values: Set<string>; longestFirst: string[] } }\nconst secretHolder = globalThis as SecretHolder\n\n// On globalThis because a Next app can bundle this module twice: the copy\n// serverEnv() registers into is not necessarily the one beforeSend reads.\nfunction secretState(): NonNullable<SecretHolder[typeof SECRETS]> {\n return (secretHolder[SECRETS] ??= { values: new Set(), longestFirst: [] })\n}\n\nexport function registerSecretValues(values: Iterable<unknown>): void {\n const state = secretState()\n for (const v of values) if (typeof v === \"string\" && v.length >= 8) state.values.add(v)\n state.longestFirst = [...state.values].sort((a, b) => b.length - a.length)\n}\n\nfunction maskSecretValues(s: string): string {\n return secretState().longestFirst.reduce((acc, v) => acc.replaceAll(v, REDACTED), s)\n}\n\nexport function redactText(s: string): string {\n return maskSecretValues(s)\n .replace(URL_USERINFO, `$1${REDACTED}@`)\n .replace(PARAMS_TAIL, \"params: [redacted]\")\n .replace(TEXT_QUERY_PARAM, (m, sep: string, k: string) =>\n SECRET_PARAMS.has(k.toLowerCase()) ? `${sep}${k}=[redacted]` : m,\n )\n .replace(AUTH_SCHEME, \"$1 [redacted]\")\n .replace(JWT, \"[jwt]\")\n .replace(EMAIL, \"[email]\")\n}\n\nfunction redactQuery(query: string): string {\n return query\n .split(\"&\")\n .map((pair) => {\n const [k, v] = pair.split(\"=\", 2)\n return v !== undefined && SECRET_PARAMS.has(k!.toLowerCase()) ? `${k}=[redacted]` : pair\n })\n .join(\"&\")\n}\n\nfunction redactUrl(url: string): string {\n const i = url.indexOf(\"?\")\n return i < 0 ? url : url.slice(0, i + 1) + redactQuery(url.slice(i + 1))\n}\n\n// For values that are either a URL/path or a bare query string (no `?`).\nfunction redactUrlOrQuery(v: string): string {\n return v.includes(\"?\") ? redactUrl(v) : redactQuery(v)\n}\n\ntype Dict = Record<string, unknown>\n\nexport interface SentryEventLike {\n server_name?: string\n user?: Dict\n request?: { url?: string; query_string?: unknown; cookies?: unknown; headers?: Record<string, string>; data?: unknown }\n message?: string\n exception?: { values?: Array<{ type?: string; value?: string }> }\n breadcrumbs?: Array<{ message?: string; data?: Dict }>\n contexts?: { nextjs?: Dict } & Dict\n}\n\nexport function scrubEvent<E extends SentryEventLike>(e: E): E {\n delete e.server_name\n if (e.user) e.user = e.user.id ? { id: e.user.id } : {}\n if (e.request) {\n delete e.request.cookies\n delete e.request.data\n if (e.request.url) e.request.url = redactUrl(e.request.url)\n if (typeof e.request.query_string === \"string\") e.request.query_string = redactQuery(e.request.query_string)\n if (e.request.headers) {\n e.request.headers = Object.fromEntries(\n Object.entries(e.request.headers).filter(([k]) => !SECRET_HEADERS.has(k.toLowerCase())),\n )\n }\n }\n const nextjs = e.contexts?.nextjs\n if (typeof nextjs?.request_path === \"string\") nextjs.request_path = redactUrl(nextjs.request_path)\n if (e.message) e.message = redactText(e.message)\n for (const v of e.exception?.values ?? []) if (v.value) v.value = redactText(v.value)\n for (const b of e.breadcrumbs ?? []) {\n if (b.message) b.message = redactText(b.message)\n const d = b.data\n if (!d) continue\n for (const k of [\"url\", \"from\", \"to\"]) if (typeof d[k] === \"string\") d[k] = redactUrl(d[k])\n if (typeof d[\"http.query\"] === \"string\") d[\"http.query\"] = redactUrlOrQuery(d[\"http.query\"])\n if (Array.isArray(d.arguments)) d.arguments = d.arguments.map((a) => (typeof a === \"string\" ? redactText(a) : a))\n }\n return e\n}\n\nexport interface SentryLogLike {\n message: string\n attributes?: Dict\n}\n\nexport function scrubLog<L extends SentryLogLike>(l: L): L {\n l.message = redactText(l.message)\n if (l.attributes) {\n const out: Dict = {}\n for (const [k, v] of Object.entries(l.attributes)) {\n if (DROP_LOG_ATTRS.has(k)) continue\n out[k] = typeof v === \"string\" ? redactText(v) : v\n }\n l.attributes = out\n }\n return l\n}\n\nexport interface SentrySpanLike {\n description?: string\n data?: Dict\n}\n\nexport function scrubSpan<S extends SentrySpanLike>(s: S): S {\n // Browser page-metric spans are described by the full page URL.\n if (typeof s.description === \"string\") s.description = redactUrl(s.description)\n for (const [k, v] of Object.entries(s.data ?? {})) {\n if (DROP_SPAN_KEYS.has(k) || DROP_SPAN_PREFIXES.some((p) => k.startsWith(p))) delete s.data![k]\n else if (REDACT_KEYS.has(k) || REDACT_PREFIXES.some((p) => k.startsWith(p))) s.data![k] = REDACTED\n else if (typeof v === \"string\" && URL_SPAN_KEYS.has(k)) s.data![k] = redactUrlOrQuery(v)\n }\n return s\n}\n"],"mappings":";AAAO,IAAM,WAAW;AAKxB,IAAM,QAAQ;AACd,IAAM,eAAe;AACrB,IAAM,MAAM;AACZ,IAAM,cAAc;AACpB,IAAM,cAAc;AAGpB,IAAM,mBAAmB;AAClB,IAAM,gBAAqC,oBAAI,IAAI,CAAC,SAAS,QAAQ,SAAS,YAAY,UAAU,OAAO,WAAW,gBAAgB,iBAAiB,YAAY,YAAY,eAAe,CAAC;AACtM,IAAM,iBAAiB,oBAAI,IAAI;AAAA,EAC7B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AACD,IAAM,iBAAiB,oBAAI,IAAI,CAAC,MAAM,cAAc,cAAc,SAAS,cAAc,gBAAgB,CAAC;AAC1G,IAAM,cAAc,oBAAI,IAAI,CAAC,wBAAwB,SAAS,CAAC;AAC/D,IAAM,kBAAkB,CAAC,aAAa,aAAa,aAAa,iBAAiB,gBAAgB;AACjG,IAAM,iBAAiB,oBAAI,IAAI,CAAC,uBAAuB,mBAAmB,kBAAkB,gBAA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c,IAAI,CAAC,EAAG,GAAE,KAAM,CAAC,IAAI,iBAAiB,CAAC;AAAA,EACzF;AACA,SAAO;AACT;","names":[]}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import {
|
|
2
2
|
initSentry
|
|
3
|
-
} from "./chunk-
|
|
3
|
+
} from "./chunk-P5GBQVO7.js";
|
|
4
4
|
import {
|
|
5
5
|
readSentryConfig
|
|
6
6
|
} from "./chunk-7ASQHY7O.js";
|
|
@@ -17,4 +17,4 @@ export {
|
|
|
17
17
|
register,
|
|
18
18
|
onRequestError
|
|
19
19
|
};
|
|
20
|
-
//# sourceMappingURL=chunk-
|
|
20
|
+
//# sourceMappingURL=chunk-WOFBDOMY.js.map
|
|
@@ -94,6 +94,22 @@ var MIGRATION_0007_EXPECTED_IDENTITY = `
|
|
|
94
94
|
ALTER TABLE auth.login_state ADD COLUMN IF NOT EXISTS expected_sub varchar(64);
|
|
95
95
|
ALTER TABLE auth.login_state ADD COLUMN IF NOT EXISTS expected_email varchar(320);
|
|
96
96
|
`;
|
|
97
|
+
var MIGRATION_0008_MOBILE = `
|
|
98
|
+
ALTER TABLE auth.sessions ADD COLUMN IF NOT EXISTS kind varchar(16) NOT NULL DEFAULT 'web';
|
|
99
|
+
ALTER TABLE auth.login_state ADD COLUMN IF NOT EXISTS mobile_challenge varchar(64);
|
|
100
|
+
ALTER TABLE auth.login_state ADD COLUMN IF NOT EXISTS mobile_redirect text;
|
|
101
|
+
ALTER TABLE auth.login_state ADD COLUMN IF NOT EXISTS ui_locales varchar(16);
|
|
102
|
+
|
|
103
|
+
CREATE TABLE IF NOT EXISTS auth.mobile_handoff_codes (
|
|
104
|
+
code_hash varchar(64) PRIMARY KEY,
|
|
105
|
+
session_id uuid NOT NULL,
|
|
106
|
+
challenge varchar(64) NOT NULL,
|
|
107
|
+
expires_at timestamptz NOT NULL
|
|
108
|
+
);
|
|
109
|
+
|
|
110
|
+
CREATE INDEX IF NOT EXISTS ix_auth_mobile_handoff_expires
|
|
111
|
+
ON auth.mobile_handoff_codes(expires_at);
|
|
112
|
+
`;
|
|
97
113
|
async function probe(db, expression) {
|
|
98
114
|
const result = await db.execute(
|
|
99
115
|
sql2.raw(`SELECT (${expression}) AS "applied"`)
|
|
@@ -169,6 +185,19 @@ var MIGRATIONS = [
|
|
|
169
185
|
["auth", "login_state", "expected_sub"],
|
|
170
186
|
["auth", "login_state", "expected_email"]
|
|
171
187
|
)
|
|
188
|
+
},
|
|
189
|
+
{
|
|
190
|
+
name: "0008_mobile",
|
|
191
|
+
sql: MIGRATION_0008_MOBILE,
|
|
192
|
+
isApplied: async (db) => await columnsExist(
|
|
193
|
+
["auth", "sessions", "kind"],
|
|
194
|
+
["auth", "login_state", "mobile_challenge"],
|
|
195
|
+
["auth", "login_state", "mobile_redirect"],
|
|
196
|
+
["auth", "login_state", "ui_locales"]
|
|
197
|
+
)(db) && await relationsExist(
|
|
198
|
+
["auth", "mobile_handoff_codes"],
|
|
199
|
+
["auth", "ix_auth_mobile_handoff_expires"]
|
|
200
|
+
)(db)
|
|
172
201
|
}
|
|
173
202
|
];
|
|
174
203
|
async function runAuthMigrations(db, opts = {}) {
|
|
@@ -194,4 +223,4 @@ export {
|
|
|
194
223
|
grantRuntimeDefaultPrivileges,
|
|
195
224
|
runAuthMigrations
|
|
196
225
|
};
|
|
197
|
-
//# sourceMappingURL=chunk-
|
|
226
|
+
//# sourceMappingURL=chunk-YCKDMG4B.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/db-core/migration-db.ts","../src/auth-core/migrate.ts"],"sourcesContent":["import { Pool } from \"pg\"\nimport { drizzle, type NodePgDatabase } from \"drizzle-orm/node-postgres\"\nimport { sql } from \"drizzle-orm\"\nimport { resolvePostgresConfig } from \"./postgres-config\"\n\nexport interface MigrationDb {\n readonly db: NodePgDatabase\n readonly close: () => Promise<void>\n}\n\n// Migrations get their own short-lived pool, separate from the app's\n// long-lived runtime pool — it exists only for the duration of the boot-time\n// migration call and is torn down immediately after.\nexport function createMigrationDb(databaseUrl: string): MigrationDb {\n const pool = new Pool(resolvePostgresConfig(databaseUrl))\n return { db: drizzle(pool), close: () => pool.end() }\n}\n\n// The addon's regular/admin credentials are both delivered as full DSNs\n// (POSTGRES_URI / POSTGRES_URI_ADMIN — see the templates SecretGroup\n// addonDependencies mapping), not as separate username/password fields, so\n// callers that need the runtime role's name for a GRANT statement parse it\n// out of the runtime connection string instead of reading it separately.\nexport function parseRoleFromUrl(databaseUrl: string): string {\n return decodeURIComponent(new URL(databaseUrl).username)\n}\n\n// `current_user` is compared as the server reports it, so the comparison holds\n// for a role whose name needed quoting in the DSN.\nasync function isCurrentUser(db: NodePgDatabase, role: string): Promise<boolean> {\n const result = await db.execute<{ current_user: string }>(\n sql.raw(`SELECT current_user AS \"current_user\"`),\n )\n return result.rows[0]?.current_user === role\n}\n\n// Safe to call on every boot, whether or not the migrator and runtime roles\n// are the same (the fallback case for environments that haven't opted into a\n// separate migration role yet — see MIGRATION_DATABASE_URL fallback in\n// portal-api/portal-web). ALTER DEFAULT PRIVILEGES only binds objects created\n// after it runs, so this also explicitly grants on ALL TABLES to cover\n// whatever this same run just created.\n//\n// The fallback case is skipped outright rather than issued anyway: granting a\n// role privileges to itself is either redundant (it owns the objects, so it\n// already holds everything) or impossible (it does not, so GRANT raises `must\n// be owner of table …` / `permission denied for schema …`). Issuing it made\n// that second case a boot-time failure on an environment where there was\n// nothing whatsoever to grant.\nexport async function grantRuntimeDefaultPrivileges(\n db: NodePgDatabase,\n schema: string,\n runtimeRole: string,\n): Promise<void> {\n if (await isCurrentUser(db, runtimeRole)) {\n return\n }\n await db.execute(\n sql.raw(`GRANT USAGE ON SCHEMA \"${schema}\" TO \"${runtimeRole}\"`),\n )\n await db.execute(\n sql.raw(\n `ALTER DEFAULT PRIVILEGES IN SCHEMA \"${schema}\" GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO \"${runtimeRole}\"`,\n ),\n )\n await db.execute(\n sql.raw(\n `GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA \"${schema}\" TO \"${runtimeRole}\"`,\n ),\n )\n}\n","import { sql } from \"drizzle-orm\"\nimport type { NodePgDatabase } from \"drizzle-orm/node-postgres\"\nimport { grantRuntimeDefaultPrivileges } from \"../db-core/migration-db\"\n\n// Migrations are inlined as string constants rather than read from .sql files\n// at runtime. A runtime `readFile` does not survive bundlers that only trace\n// JS — notably Next.js standalone output, where the .sql is omitted and the\n// read ENOENTs, crashing the instrumentation hook and 500-ing the whole app.\n// Inlining keeps the SQL in the bundled JS so it works in every consumer.\n\n// Split out of what used to be a single MIGRATION_0001_INIT on purpose, and\n// the reason generalises to every statement below it: **Postgres checks the\n// connecting role's privileges before it evaluates `IF NOT EXISTS`.** So an\n// already-applied statement is not a no-op for a role that lacks the right —\n// it is an error:\n//\n// - `CREATE SCHEMA IF NOT EXISTS auth` needs CREATE on the *database* →\n// `permission denied for database <db>` (SQLSTATE 42501)\n// - `CREATE INDEX IF NOT EXISTS` and `ALTER TABLE ... ADD COLUMN IF NOT\n// EXISTS` need *ownership* of the table → `must be owner of table\n// sessions` (also 42501)\n//\n// That is the normal shape of a least-privileged runtime role against an\n// already-provisioned database, and because migrations run in order one such\n// error aborts every statement after it. It has now bitten staging twice: the\n// first time `login_state.forced_reauth` never landed and every\n// `/api/auth/login` 500'd; the second time `0001_init:tables` failed on its\n// `CREATE INDEX` with `must be owner of table sessions`, again blocking every\n// later ALTER even though there was nothing at all to do.\n//\n// So each migration below carries an `isApplied` catalog probe and the runner\n// skips it when its effect is already present. Catalog lookups need nothing\n// beyond CONNECT, so a role with only DML inside an up-to-date `auth` schema\n// gets through cleanly, while a migration that genuinely still has work to do\n// is attempted and — if the role cannot do it — fails loudly, by name.\nconst MIGRATION_0001_SCHEMA = `\nCREATE SCHEMA IF NOT EXISTS auth;\n`\n\nconst MIGRATION_0001_TABLES = `\nCREATE TABLE IF NOT EXISTS auth.sessions (\n id uuid PRIMARY KEY DEFAULT gen_random_uuid(),\n user_sub varchar(64) NOT NULL,\n user_email varchar(320),\n organization_id varchar(64),\n organization_alias varchar(255),\n access_token text NOT NULL,\n access_expires_at timestamptz NOT NULL,\n refresh_ct bytea NOT NULL,\n refresh_iv bytea NOT NULL,\n refresh_expires_at timestamptz NOT NULL,\n created_at timestamptz NOT NULL DEFAULT now(),\n updated_at timestamptz NOT NULL DEFAULT now(),\n revoked_at timestamptz\n);\n\nCREATE INDEX IF NOT EXISTS ix_auth_sessions_user_sub\n ON auth.sessions(user_sub) WHERE revoked_at IS NULL;\n\nCREATE TABLE IF NOT EXISTS auth.login_state (\n state varchar(128) PRIMARY KEY,\n code_verifier varchar(255) NOT NULL,\n redirect_path text NOT NULL DEFAULT '/',\n created_at timestamptz NOT NULL DEFAULT now(),\n expires_at timestamptz NOT NULL\n);\n\nCREATE INDEX IF NOT EXISTS ix_auth_login_state_expires\n ON auth.login_state(expires_at);\n`\n\n// The KC ID token, so RP-initiated logout can pass it as `id_token_hint` —\n// without it, Keycloak's end-session endpoint falls back to showing a logout\n// confirmation page. Nullable: existing sessions predate this column until\n// their next login or token refresh backfills it.\nconst MIGRATION_0002_ID_TOKEN = `\nALTER TABLE auth.sessions ADD COLUMN IF NOT EXISTS id_token text;\n`\n\n// Records that this login asked Keycloak to re-authenticate (prompt=login +\n// max_age=0). The callback needs it to know whether the ID token's auth_time\n// MUST prove a fresh authentication (OIDC 3.1.2.1) — without the flag it cannot\n// tell a forced login from an ordinary SSO continuation.\nconst MIGRATION_0003_FORCED_REAUTH = `\nALTER TABLE auth.login_state ADD COLUMN IF NOT EXISTS forced_reauth boolean NOT NULL DEFAULT false;\n`\n\n// OIDC 3.1.3.7 (11): the nonce sent on the authorization request must be\n// checked against the ID token's claim. Nullable because rows written by an\n// older build have none; the callback treats a null nonce on the row as\n// \"nothing to check\" so an in-flight login survives the deploy.\nconst MIGRATION_0004_NONCE = `\nALTER TABLE auth.login_state ADD COLUMN IF NOT EXISTS nonce varchar(128);\n`\n\n// Bounds the one-and-only restart the callback grants on Keycloak's explicit\n// \"start over\" signals (authentication_expired / login_required). The\n// callback URL is Keycloak's fixed redirect_uri, so Keycloak never echoes our\n// own query parameters back to it — a guard read off the callback's query\n// string can never fire in production. The restarted login (our own request\n// to /api/auth/login?retried=1) stamps this column on the NEW row instead, so\n// the second callback can see it on the row rather than in a URL Keycloak\n// controls. NOT NULL DEFAULT false: every row, old or new, starts un-retried.\nconst MIGRATION_0005_RETRIED = `\nALTER TABLE auth.login_state ADD COLUMN IF NOT EXISTS retried boolean NOT NULL DEFAULT false;\n`\n\n// A session created for an identity that did not match what the login expected\n// exists, holds real tokens, and grants nothing until a human confirms it.\n//\n// DELIBERATELY `DEFAULT false` rather than a nullable column with a backfill:\n// these migrations re-run on every app start, so an `UPDATE ... WHERE\n// pending_identity_confirm IS NULL` would confirm every row still awaiting a\n// human on the next deploy — silently adopting exactly the identity this\n// mechanism exists to stop. A default means pre-existing rows are already\n// confirmed, which is correct: they were issued under the old rules.\nconst MIGRATION_0006_PENDING_CONFIRM = `\nALTER TABLE auth.sessions\n ADD COLUMN IF NOT EXISTS pending_identity_confirm boolean NOT NULL DEFAULT false;\n`\n\n// Who this login was supposed to end up as: the subject of the session being\n// replaced, and/or the address the user typed. The callback compares Keycloak's\n// answer against these instead of adopting whatever comes back. Nullable: a\n// clean first login on a fresh browser expects nobody in particular.\nconst MIGRATION_0007_EXPECTED_IDENTITY = `\nALTER TABLE auth.login_state ADD COLUMN IF NOT EXISTS expected_sub varchar(64);\nALTER TABLE auth.login_state ADD COLUMN IF NOT EXISTS expected_email varchar(320);\n`\n\n// Mobile sign-in (`createAuthRouteHandlers({ mobile })`). A phone has no cookie\n// jar the browser shares with the app, so a mobile login ends in a one-shot\n// handoff code instead of a cookie: the callback stores it hashed, bound to the\n// app's PKCE challenge, and the app redeems it for its session token within a\n// minute. `sessions.kind` decides which lifetime bounds a session lives under\n// and whether a bearer token may present it; DEFAULT 'web' makes every existing\n// row what it already was. The login_state columns carry the mobile request\n// (challenge, return URL, locale) from /mobile/login to the callback. All\n// nullable or defaulted, so the previous release keeps working on this shape.\nconst MIGRATION_0008_MOBILE = `\nALTER TABLE auth.sessions ADD COLUMN IF NOT EXISTS kind varchar(16) NOT NULL DEFAULT 'web';\nALTER TABLE auth.login_state ADD COLUMN IF NOT EXISTS mobile_challenge varchar(64);\nALTER TABLE auth.login_state ADD COLUMN IF NOT EXISTS mobile_redirect text;\nALTER TABLE auth.login_state ADD COLUMN IF NOT EXISTS ui_locales varchar(16);\n\nCREATE TABLE IF NOT EXISTS auth.mobile_handoff_codes (\n code_hash varchar(64) PRIMARY KEY,\n session_id uuid NOT NULL,\n challenge varchar(64) NOT NULL,\n expires_at timestamptz NOT NULL\n);\n\nCREATE INDEX IF NOT EXISTS ix_auth_mobile_handoff_expires\n ON auth.mobile_handoff_codes(expires_at);\n`\n\ninterface Migration {\n // Named so a failure can say *which* statement broke — see the catch below.\n readonly name: string\n readonly sql: string\n // \"Is this migration's effect already present?\" Answered from the catalogs\n // only, so it never needs a privilege the migration itself would need. A\n // partially-applied migration must answer `false` (the SQL is written to be\n // idempotent, so re-running the applied half is harmless).\n readonly isApplied: (db: NodePgDatabase) => Promise<boolean>\n // A migration may only add to the schema: a prod rollback keeps the\n // database, and the previous release must still work on it\n // (scripts/migration-lint.mjs refuses anything else). `true` marks the rare\n // migration that removes or tightens something on purpose; ship it only once\n // no prod still runs a version that reads the old shape.\n readonly contract?: boolean\n}\n\n// All probes funnel through here: one boolean expression, evaluated by the\n// server. Every one of them reads `pg_catalog` directly rather than going\n// through `to_regclass`/`to_regnamespace` or `information_schema`, both of\n// which are privilege-sensitive in ways that defeat the purpose: `to_regclass`\n// resolves the name and so raises `permission denied for schema auth` for a\n// role without USAGE, and `information_schema.columns` silently hides columns\n// the role holds no privilege on — reporting an applied migration as missing\n// and sending us straight into the ALTER we were trying to avoid. The catalogs\n// themselves are world-readable.\nasync function probe(db: NodePgDatabase, expression: string): Promise<boolean> {\n const result = await db.execute<{ applied: boolean }>(\n sql.raw(`SELECT (${expression}) AS \"applied\"`),\n )\n return result.rows[0]?.applied === true\n}\n\nconst schemaExists = (schema: string) => (db: NodePgDatabase) =>\n probe(db, `EXISTS (SELECT 1 FROM pg_namespace WHERE nspname = '${schema}')`)\n\n// Tables and indexes alike — both live in `pg_class`.\nconst relationsExist =\n (...relations: readonly (readonly [schema: string, name: string])[]) =>\n (db: NodePgDatabase) => {\n const tuples = relations.map(([schema, name]) => `('${schema}','${name}')`).join(\", \")\n return probe(\n db,\n `(SELECT count(*) FROM pg_class c\n JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE (n.nspname, c.relname) IN (${tuples})) = ${relations.length}`,\n )\n }\n\nconst columnsExist =\n (...columns: readonly (readonly [schema: string, table: string, column: string])[]) =>\n (db: NodePgDatabase) => {\n const tuples = columns\n .map(([schema, table, column]) => `('${schema}','${table}','${column}')`)\n .join(\", \")\n return probe(\n db,\n `(SELECT count(*) FROM pg_attribute a\n JOIN pg_class c ON c.oid = a.attrelid\n JOIN pg_namespace n ON n.oid = c.relnamespace\n WHERE a.attnum > 0 AND NOT a.attisdropped\n AND (n.nspname, c.relname, a.attname) IN (${tuples})) = ${columns.length}`,\n )\n }\n\nconst MIGRATIONS: readonly Migration[] = [\n {\n name: \"0001_init:schema\",\n sql: MIGRATION_0001_SCHEMA,\n isApplied: schemaExists(\"auth\"),\n },\n {\n name: \"0001_init:tables\",\n sql: MIGRATION_0001_TABLES,\n isApplied: relationsExist(\n [\"auth\", \"sessions\"],\n [\"auth\", \"ix_auth_sessions_user_sub\"],\n [\"auth\", \"login_state\"],\n [\"auth\", \"ix_auth_login_state_expires\"],\n ),\n },\n {\n name: \"0002_id_token\",\n sql: MIGRATION_0002_ID_TOKEN,\n isApplied: columnsExist([\"auth\", \"sessions\", \"id_token\"]),\n },\n {\n name: \"0003_forced_reauth\",\n sql: MIGRATION_0003_FORCED_REAUTH,\n isApplied: columnsExist([\"auth\", \"login_state\", \"forced_reauth\"]),\n },\n {\n name: \"0004_nonce\",\n sql: MIGRATION_0004_NONCE,\n isApplied: columnsExist([\"auth\", \"login_state\", \"nonce\"]),\n },\n {\n name: \"0005_retried\",\n sql: MIGRATION_0005_RETRIED,\n isApplied: columnsExist([\"auth\", \"login_state\", \"retried\"]),\n },\n {\n name: \"0006_pending_confirm\",\n sql: MIGRATION_0006_PENDING_CONFIRM,\n isApplied: columnsExist([\"auth\", \"sessions\", \"pending_identity_confirm\"]),\n },\n {\n name: \"0007_expected_identity\",\n sql: MIGRATION_0007_EXPECTED_IDENTITY,\n isApplied: columnsExist(\n [\"auth\", \"login_state\", \"expected_sub\"],\n [\"auth\", \"login_state\", \"expected_email\"],\n ),\n },\n {\n name: \"0008_mobile\",\n sql: MIGRATION_0008_MOBILE,\n isApplied: async (db) =>\n (await columnsExist(\n [\"auth\", \"sessions\", \"kind\"],\n [\"auth\", \"login_state\", \"mobile_challenge\"],\n [\"auth\", \"login_state\", \"mobile_redirect\"],\n [\"auth\", \"login_state\", \"ui_locales\"],\n )(db)) &&\n (await relationsExist(\n [\"auth\", \"mobile_handoff_codes\"],\n [\"auth\", \"ix_auth_mobile_handoff_expires\"],\n )(db)),\n },\n]\n\nexport interface RunAuthMigrationsOptions {\n // When provided, grants this role SELECT/INSERT/UPDATE/DELETE on every\n // table in the `auth` schema — both ones this call just created and ones a\n // future boot's migrations will create. Omit for a single-role setup (the\n // fallback state of an environment that hasn't opted into a separate\n // migration role yet); passing it is what makes it safe for `db` to\n // connect as an admin/owner role while the app itself never does.\n readonly runtimeRole?: string\n}\n\nexport async function runAuthMigrations(\n db: NodePgDatabase,\n opts: RunAuthMigrationsOptions = {},\n): Promise<void> {\n for (const migration of MIGRATIONS) {\n try {\n if (await migration.isApplied(db)) {\n // Already there — do not issue the statement at all. See the comment\n // above MIGRATION_0001_SCHEMA for why relying on `IF NOT EXISTS` to make\n // it a no-op is not safe under every role.\n continue\n }\n await db.execute(sql.raw(migration.sql))\n } catch (err) {\n // Re-thrown, not swallowed: the caller decides what to do with a failed\n // migration. Naming the statement is what turns a bare \"permission\n // denied for database x\" into something you can actually act on; the\n // `cause` keeps the original Postgres error (code, detail, etc.) intact.\n const message = err instanceof Error ? err.message : String(err)\n throw new Error(`auth migration \"${migration.name}\" failed: ${message}`, { cause: err })\n }\n }\n\n if (opts.runtimeRole) {\n await grantRuntimeDefaultPrivileges(db, \"auth\", opts.runtimeRole)\n }\n}\n"],"mappings":";;;;;AAAA,SAAS,YAAY;AACrB,SAAS,eAAoC;AAC7C,SAAS,WAAW;AAWb,SAAS,kBAAkB,aAAkC;AAClE,QAAM,OAAO,IAAI,KAAK,sBAAsB,WAAW,CAAC;AACxD,SAAO,EAAE,IAAI,QAAQ,IAAI,GAAG,OAAO,MAAM,KAAK,IAAI,EAAE;AACtD;AAOO,SAAS,iBAAiB,aAA6B;AAC5D,SAAO,mBAAmB,IAAI,IAAI,WAAW,EAAE,QAAQ;AACzD;AAIA,eAAe,cAAc,IAAoB,MAAgC;AAC/E,QAAM,SAAS,MAAM,GAAG;AAAA,IACtB,IAAI,IAAI,uCAAuC;AAAA,EACjD;AACA,SAAO,OAAO,KAAK,CAAC,GAAG,iBAAiB;AAC1C;AAeA,eAAsB,8BACpB,IACA,QACA,aACe;AACf,MAAI,MAAM,cAAc,IAAI,WAAW,GAAG;AACxC;AAAA,EACF;AACA,QAAM,GAAG;AAAA,IACP,IAAI,IAAI,0BAA0B,MAAM,SAAS,WAAW,GAAG;AAAA,EACjE;AACA,QAAM,GAAG;AAAA,IACP,IAAI;AAAA,MACF,uCAAuC,MAAM,wDAAwD,WAAW;AAAA,IAClH;AAAA,EACF;AACA,QAAM,GAAG;AAAA,IACP,IAAI;AAAA,MACF,iEAAiE,MAAM,SAAS,WAAW;AAAA,IAC7F;AAAA,EACF;AACF;;;ACtEA,SAAS,OAAAA,YAAW;AAmCpB,IAAM,wBAAwB;AAAA;AAAA;AAI9B,IAAM,wBAAwB;AAAA;AAAA;AA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kB;AAAA,MAC1C,CAAC,QAAQ,eAAe,iBAAiB;AAAA,MACzC,CAAC,QAAQ,eAAe,YAAY;AAAA,IACtC,EAAE,EAAE,KACH,MAAM;AAAA,MACL,CAAC,QAAQ,sBAAsB;AAAA,MAC/B,CAAC,QAAQ,gCAAgC;AAAA,IAC3C,EAAE,EAAE;AAAA,EACR;AACF;AAYA,eAAsB,kBACpB,IACA,OAAiC,CAAC,GACnB;AACf,aAAW,aAAa,YAAY;AAClC,QAAI;AACF,UAAI,MAAM,UAAU,UAAU,EAAE,GAAG;AAIjC;AAAA,MACF;AACA,YAAM,GAAG,QAAQA,KAAI,IAAI,UAAU,GAAG,CAAC;AAAA,IACzC,SAAS,KAAK;AAKZ,YAAM,UAAU,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAC/D,YAAM,IAAI,MAAM,mBAAmB,UAAU,IAAI,aAAa,OAAO,IAAI,EAAE,OAAO,IAAI,CAAC;AAAA,IACzF;AAAA,EACF;AAEA,MAAI,KAAK,aAAa;AACpB,UAAM,8BAA8B,IAAI,QAAQ,KAAK,WAAW;AAAA,EAClE;AACF;","names":["sql","sql"]}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import {
|
|
2
|
+
ApiError,
|
|
3
|
+
Unauthenticated
|
|
4
|
+
} from "./chunk-JM5LHJUJ.js";
|
|
5
|
+
|
|
6
|
+
// src/expo/auth/context.tsx
|
|
7
|
+
import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState } from "react";
|
|
8
|
+
import { Fragment, jsx } from "react/jsx-runtime";
|
|
9
|
+
var AuthContext = createContext(null);
|
|
10
|
+
async function loadStatus(auth, onProblem) {
|
|
11
|
+
if (!await auth.hasSession()) return { state: "signedOut" };
|
|
12
|
+
try {
|
|
13
|
+
return { state: "signedIn", me: await auth.apiFetch("/api/auth/me") };
|
|
14
|
+
} catch (err) {
|
|
15
|
+
if (err instanceof Unauthenticated) return { state: "signedOut", notice: { reason: "session_ended" } };
|
|
16
|
+
if (err instanceof ApiError && err.code === "no_app_access") {
|
|
17
|
+
await auth.logout();
|
|
18
|
+
return { state: "signedOut", notice: { reason: "no_app_access" } };
|
|
19
|
+
}
|
|
20
|
+
const detail = err instanceof ApiError ? `http_${err.status}` : "network";
|
|
21
|
+
onProblem?.("auth.me.unreachable", detail);
|
|
22
|
+
return { state: "error", detail };
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
function QoreAuthProvider({ auth, children, disabled, onUserChange, onProblem }) {
|
|
26
|
+
const [status, setStatus] = useState(disabled ? { state: "signedOut" } : { state: "loading" });
|
|
27
|
+
const problemRef = useRef(onProblem);
|
|
28
|
+
problemRef.current = onProblem;
|
|
29
|
+
const userRef = useRef(onUserChange);
|
|
30
|
+
userRef.current = onUserChange;
|
|
31
|
+
const refresh = useCallback(async () => {
|
|
32
|
+
if (disabled) return setStatus({ state: "signedOut" });
|
|
33
|
+
setStatus(await loadStatus(auth, problemRef.current));
|
|
34
|
+
}, [auth, disabled]);
|
|
35
|
+
useEffect(() => {
|
|
36
|
+
void refresh();
|
|
37
|
+
}, [refresh]);
|
|
38
|
+
const sub = status.state === "signedIn" ? status.me.sub : null;
|
|
39
|
+
useEffect(() => userRef.current?.(sub), [sub]);
|
|
40
|
+
const signIn = useCallback(
|
|
41
|
+
async (locale) => {
|
|
42
|
+
const result = await auth.login(locale);
|
|
43
|
+
if (result.ok) return refresh();
|
|
44
|
+
if (result.reason === "cancelled") return;
|
|
45
|
+
problemRef.current?.("auth.login.failed", result.detail ?? result.reason);
|
|
46
|
+
setStatus({ state: "signedOut", notice: { reason: result.reason, detail: result.detail } });
|
|
47
|
+
},
|
|
48
|
+
[auth, refresh]
|
|
49
|
+
);
|
|
50
|
+
const signOut = useCallback(async () => {
|
|
51
|
+
await auth.logout();
|
|
52
|
+
setStatus({ state: "signedOut" });
|
|
53
|
+
}, [auth]);
|
|
54
|
+
const expire = useCallback(() => setStatus({ state: "signedOut", notice: { reason: "session_ended" } }), []);
|
|
55
|
+
const value = useMemo(() => ({ status, signIn, signOut, refresh, expire, auth }), [status, signIn, signOut, refresh, expire, auth]);
|
|
56
|
+
return /* @__PURE__ */ jsx(AuthContext.Provider, { value, children });
|
|
57
|
+
}
|
|
58
|
+
var AuthContextProvider = AuthContext.Provider;
|
|
59
|
+
function useAuth() {
|
|
60
|
+
const ctx = useContext(AuthContext);
|
|
61
|
+
if (!ctx) throw new Error("useAuth must be used inside <QoreAuthProvider>");
|
|
62
|
+
return ctx;
|
|
63
|
+
}
|
|
64
|
+
function useMe() {
|
|
65
|
+
const { status } = useAuth();
|
|
66
|
+
return status.state === "signedIn" ? status.me : null;
|
|
67
|
+
}
|
|
68
|
+
function useCan(permission) {
|
|
69
|
+
return useMe()?.permissions.includes(permission) ?? false;
|
|
70
|
+
}
|
|
71
|
+
function Can({ permission, children, fallback = null }) {
|
|
72
|
+
return /* @__PURE__ */ jsx(Fragment, { children: useCan(permission) ? children : fallback });
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export {
|
|
76
|
+
QoreAuthProvider,
|
|
77
|
+
AuthContextProvider,
|
|
78
|
+
useAuth,
|
|
79
|
+
useMe,
|
|
80
|
+
useCan,
|
|
81
|
+
Can
|
|
82
|
+
};
|
|
83
|
+
//# sourceMappingURL=chunk-YJZZURE4.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/expo/auth/context.tsx"],"sourcesContent":["// React state over a `MobileAuth`. Shared by `expo/auth` and `expo/testing`,\n// so a component test drives the same provider the app runs.\nimport { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState, type ReactNode } from \"react\"\nimport { ApiError, Unauthenticated } from \"../core/errors\"\nimport type { LoginFailure, Me, MobileAuth } from \"./client\"\n\n/** Why the login screen is showing; the app turns it into text. */\nexport type SignedOutNotice = { reason: \"session_ended\" } | { reason: Exclude<LoginFailure, \"cancelled\">; detail?: string }\n\nexport type AuthStatus =\n | { state: \"loading\" }\n | { state: \"signedOut\"; notice?: SignedOutNotice }\n | { state: \"signedIn\"; me: Me }\n /** The server could not be reached. The token is kept: a network error is not a logout. */\n | { state: \"error\"; detail: string }\n\nexport interface AuthContextValue {\n status: AuthStatus\n /** Signs in with Keycloak's pages in `locale`. A cancelled login leaves the status as it was. */\n signIn(locale: string): Promise<void>\n signOut(): Promise<void>\n /** Re-reads `/api/auth/me`. */\n refresh(): Promise<void>\n /** A screen got `Unauthenticated`: the token is already cleared, show the login screen. */\n expire(): void\n /** The auth client, for `apiFetch` and `openPasswordReset`. */\n auth: MobileAuth\n}\n\nconst AuthContext = createContext<AuthContextValue | null>(null)\n\nexport interface QoreAuthProviderProps {\n auth: MobileAuth\n children: ReactNode\n /** Skip the server entirely and show the login screen, e.g. while the app's config is invalid. */\n disabled?: boolean\n /** Called with the Keycloak subject on sign-in and null on sign-out, e.g. `setTelemetryUser`. Never the email. */\n onUserChange?: (sub: string | null) => void\n /** Called on a failed login or an unreachable server, for the app's log. Holds no personal data. */\n onProblem?: (event: \"auth.login.failed\" | \"auth.me.unreachable\", detail: string) => void\n}\n\nasync function loadStatus(auth: MobileAuth, onProblem: QoreAuthProviderProps[\"onProblem\"]): Promise<AuthStatus> {\n if (!(await auth.hasSession())) return { state: \"signedOut\" }\n try {\n return { state: \"signedIn\", me: await auth.apiFetch<Me>(\"/api/auth/me\") }\n } catch (err) {\n if (err instanceof Unauthenticated) return { state: \"signedOut\", notice: { reason: \"session_ended\" } }\n if (err instanceof ApiError && err.code === \"no_app_access\") {\n await auth.logout()\n return { state: \"signedOut\", notice: { reason: \"no_app_access\" } }\n }\n const detail = err instanceof ApiError ? `http_${err.status}` : \"network\"\n onProblem?.(\"auth.me.unreachable\", detail)\n return { state: \"error\", detail }\n }\n}\n\nexport function QoreAuthProvider({ auth, children, disabled, onUserChange, onProblem }: QoreAuthProviderProps) {\n const [status, setStatus] = useState<AuthStatus>(disabled ? { state: \"signedOut\" } : { state: \"loading\" })\n // Callbacks are read through refs so an inline arrow does not reload the session on every render.\n const problemRef = useRef(onProblem)\n problemRef.current = onProblem\n const userRef = useRef(onUserChange)\n userRef.current = onUserChange\n\n const refresh = useCallback(async () => {\n if (disabled) return setStatus({ state: \"signedOut\" })\n setStatus(await loadStatus(auth, problemRef.current))\n }, [auth, disabled])\n\n useEffect(() => {\n void refresh()\n }, [refresh])\n\n const sub = status.state === \"signedIn\" ? status.me.sub : null\n useEffect(() => userRef.current?.(sub), [sub])\n\n const signIn = useCallback(\n async (locale: string) => {\n const result = await auth.login(locale)\n if (result.ok) return refresh()\n if (result.reason === \"cancelled\") return\n problemRef.current?.(\"auth.login.failed\", result.detail ?? result.reason)\n setStatus({ state: \"signedOut\", notice: { reason: result.reason, detail: result.detail } })\n },\n [auth, refresh],\n )\n\n const signOut = useCallback(async () => {\n await auth.logout()\n setStatus({ state: \"signedOut\" })\n }, [auth])\n\n const expire = useCallback(() => setStatus({ state: \"signedOut\", notice: { reason: \"session_ended\" } }), [])\n\n const value = useMemo(() => ({ status, signIn, signOut, refresh, expire, auth }), [status, signIn, signOut, refresh, expire, auth])\n return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>\n}\n\n/** Internal: lets `expo/testing` provide a fixed value. */\nexport const AuthContextProvider = AuthContext.Provider\n\nexport function useAuth(): AuthContextValue {\n const ctx = useContext(AuthContext)\n if (!ctx) throw new Error(\"useAuth must be used inside <QoreAuthProvider>\")\n return ctx\n}\n\n/** The signed-in user, or null. For screens behind the signed-in guard. */\nexport function useMe(): Me | null {\n const { status } = useAuth()\n return status.state === \"signedIn\" ? status.me : null\n}\n\n/**\n * Whether the signed-in user holds `permission` (the server's\n * `src/lib/permissions.ts`). For showing or hiding UI only: the server checks\n * every request again.\n */\nexport function useCan(permission: string): boolean {\n return useMe()?.permissions.includes(permission) ?? false\n}\n\n/** Renders `children` only when the user holds `permission`; `fallback` otherwise. UI only, like `useCan`. */\nexport function Can({ permission, children, fallback = null }: { permission: string; children: ReactNode; fallback?: ReactNode }) {\n return <>{useCan(permission) ? children : f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SAAS,IAAI,EAAE,YAAY,UAAU,WAAW,KAAK,GAAsE;AAChI,SAAO,gCAAG,iBAAO,UAAU,IAAI,WAAW,UAAS;AACrD;","names":[]}
|
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
// src/cli/skills-postinstall.ts
|
|
4
4
|
import { execFileSync } from "child_process";
|
|
5
5
|
import { existsSync as existsSync2, readFileSync as readFileSync2, realpathSync as realpathSync2 } from "fs";
|
|
6
|
-
import { dirname as dirname2, join as join2, resolve as resolve2, sep } from "path";
|
|
6
|
+
import { basename, dirname as dirname2, join as join2, resolve as resolve2, sep } from "path";
|
|
7
7
|
import { fileURLToPath as fileURLToPath2 } from "url";
|
|
8
8
|
|
|
9
9
|
// src/cli/skills-core.ts
|
|
@@ -20,14 +20,17 @@ function parseFeatures(raw) {
|
|
|
20
20
|
if (!RUNTIMES.includes(o.runtime)) throw new Error(`features.runtime must be one of ${RUNTIMES.join("|")}`);
|
|
21
21
|
if (!AUTHS.includes(o.auth)) throw new Error(`features.auth must be one of ${AUTHS.join("|")}`);
|
|
22
22
|
if (typeof o.db !== "boolean") throw new Error("features.db must be a boolean");
|
|
23
|
-
|
|
23
|
+
if (o.mobile !== void 0 && typeof o.mobile !== "boolean") throw new Error("features.mobile must be a boolean");
|
|
24
|
+
if (o.mobile === true && o.runtime !== "next") throw new Error("features.mobile needs runtime next");
|
|
25
|
+
return { runtime: o.runtime, auth: o.auth, db: o.db, mobile: o.mobile === true };
|
|
24
26
|
}
|
|
25
27
|
function inferFeatures(pkg, exists) {
|
|
26
28
|
const deps = { ...pkg.devDependencies, ...pkg.dependencies };
|
|
27
29
|
const runtime = "next" in deps ? "next" : "node";
|
|
28
30
|
const auth = "better-auth" in deps ? "betterauth" : exists("src/lib/permissions.ts") ? "keycloak" : "none";
|
|
29
31
|
const db = "drizzle-orm" in deps || Boolean(pkg.scripts?.["db:up"]) || exists("docker-compose.yml");
|
|
30
|
-
|
|
32
|
+
const mobile = runtime === "next" && exists("mobile/package.json");
|
|
33
|
+
return { runtime, auth, db, mobile };
|
|
31
34
|
}
|
|
32
35
|
function evalCondition(expr, f) {
|
|
33
36
|
const e = expr.trim();
|
|
@@ -43,6 +46,9 @@ function evalCondition(expr, f) {
|
|
|
43
46
|
case "db":
|
|
44
47
|
if (options) throw new Error(`condition "${e}" takes no value`);
|
|
45
48
|
return f.db;
|
|
49
|
+
case "mobile":
|
|
50
|
+
if (options) throw new Error(`condition "${e}" takes no value`);
|
|
51
|
+
return f.mobile;
|
|
46
52
|
default:
|
|
47
53
|
throw new Error(`unknown condition "${e}"`);
|
|
48
54
|
}
|
|
@@ -66,7 +72,7 @@ function renderTemplate(src, f) {
|
|
|
66
72
|
const tag = m[1];
|
|
67
73
|
if (tag.startsWith("#if ")) {
|
|
68
74
|
const cond = tag.slice(4).trim();
|
|
69
|
-
evalCondition(cond, { runtime: "next", auth: "none", db: false });
|
|
75
|
+
evalCondition(cond, { runtime: "next", auth: "none", db: false, mobile: false });
|
|
70
76
|
const node = { cond, then: [], else: [] };
|
|
71
77
|
push(node);
|
|
72
78
|
stack.push({ node, inElse: false });
|
|
@@ -165,7 +171,7 @@ extension file.
|
|
|
165
171
|
|
|
166
172
|
\`qore-add-env-key\`, \`qore-add-integration\`, \`qore-add-connection\`,
|
|
167
173
|
\`qore-use-permissions\`, \`qore-observability\` and \`qore-use-database\`
|
|
168
|
-
produce code the portal reads: the
|
|
174
|
+
produce code the portal reads: the Variables tab, the Integrations tab,
|
|
169
175
|
connections, roles, Monitoring, the local database. An
|
|
170
176
|
extension may add to them but not relax them, and turning one off does not turn
|
|
171
177
|
off the SDK's lint rules that check the same things.
|
|
@@ -411,7 +417,7 @@ function renderReport(p, opts) {
|
|
|
411
417
|
const lines = [
|
|
412
418
|
"### Qore skills",
|
|
413
419
|
"",
|
|
414
|
-
`${opts.check ? "Out of date: `qore-skills sync` would update" : "Synced"} the managed skills for \`@quatronic/sdk@${p.manifest.sdkVersion}\` (runtime \`${f.runtime}\`, auth \`${f.auth}\`, database \`${f.db ? "yes" : "no"}\`${opts.inferred ? ", inferred from the app \u2014 pin with `qore-skills sync --features`" : ", pinned in the manifest"}).`
|
|
420
|
+
`${opts.check ? "Out of date: `qore-skills sync` would update" : "Synced"} the managed skills for \`@quatronic/sdk@${p.manifest.sdkVersion}\` (runtime \`${f.runtime}\`, auth \`${f.auth}\`, database \`${f.db ? "yes" : "no"}\`${f.mobile ? ", mobile app `yes`" : ""}${opts.inferred ? ", inferred from the app \u2014 pin with `qore-skills sync --features`" : ", pinned in the manifest"}).`
|
|
415
421
|
];
|
|
416
422
|
const managedWrites = [...p.writes.keys()].filter((r) => r !== MANIFEST_PATH);
|
|
417
423
|
if (!managedWrites.length && !p.deletes.length && p.claudeMd === void 0) {
|
|
@@ -661,6 +667,7 @@ function runPostinstall(e) {
|
|
|
661
667
|
if (!e.self.split(sep).includes("node_modules")) return { kind: "not-installed" };
|
|
662
668
|
const app = findApp(e.env.INIT_CWD ?? process.cwd());
|
|
663
669
|
if (!app) return { kind: "no-app" };
|
|
670
|
+
if (basename(app) === "mobile" && dependsOnSdk(dirname2(app))) return { kind: "mobile-project" };
|
|
664
671
|
if (!existsSync2(join2(app, ".git"))) return { kind: "not-a-checkout" };
|
|
665
672
|
const manifestPath = join2(app, ".claude", MANIFEST_PATH);
|
|
666
673
|
const manifest = existsSync2(manifestPath) ? parseManifest(readFileSync2(manifestPath, "utf8")) : null;
|
package/dist/cli/skills.js
CHANGED
|
@@ -19,14 +19,17 @@ function parseFeatures(raw) {
|
|
|
19
19
|
if (!RUNTIMES.includes(o.runtime)) throw new Error(`features.runtime must be one of ${RUNTIMES.join("|")}`);
|
|
20
20
|
if (!AUTHS.includes(o.auth)) throw new Error(`features.auth must be one of ${AUTHS.join("|")}`);
|
|
21
21
|
if (typeof o.db !== "boolean") throw new Error("features.db must be a boolean");
|
|
22
|
-
|
|
22
|
+
if (o.mobile !== void 0 && typeof o.mobile !== "boolean") throw new Error("features.mobile must be a boolean");
|
|
23
|
+
if (o.mobile === true && o.runtime !== "next") throw new Error("features.mobile needs runtime next");
|
|
24
|
+
return { runtime: o.runtime, auth: o.auth, db: o.db, mobile: o.mobile === true };
|
|
23
25
|
}
|
|
24
26
|
function inferFeatures(pkg, exists) {
|
|
25
27
|
const deps = { ...pkg.devDependencies, ...pkg.dependencies };
|
|
26
28
|
const runtime = "next" in deps ? "next" : "node";
|
|
27
29
|
const auth = "better-auth" in deps ? "betterauth" : exists("src/lib/permissions.ts") ? "keycloak" : "none";
|
|
28
30
|
const db = "drizzle-orm" in deps || Boolean(pkg.scripts?.["db:up"]) || exists("docker-compose.yml");
|
|
29
|
-
|
|
31
|
+
const mobile = runtime === "next" && exists("mobile/package.json");
|
|
32
|
+
return { runtime, auth, db, mobile };
|
|
30
33
|
}
|
|
31
34
|
function evalCondition(expr, f) {
|
|
32
35
|
const e = expr.trim();
|
|
@@ -42,6 +45,9 @@ function evalCondition(expr, f) {
|
|
|
42
45
|
case "db":
|
|
43
46
|
if (options) throw new Error(`condition "${e}" takes no value`);
|
|
44
47
|
return f.db;
|
|
48
|
+
case "mobile":
|
|
49
|
+
if (options) throw new Error(`condition "${e}" takes no value`);
|
|
50
|
+
return f.mobile;
|
|
45
51
|
default:
|
|
46
52
|
throw new Error(`unknown condition "${e}"`);
|
|
47
53
|
}
|
|
@@ -65,7 +71,7 @@ function renderTemplate(src, f) {
|
|
|
65
71
|
const tag = m[1];
|
|
66
72
|
if (tag.startsWith("#if ")) {
|
|
67
73
|
const cond = tag.slice(4).trim();
|
|
68
|
-
evalCondition(cond, { runtime: "next", auth: "none", db: false });
|
|
74
|
+
evalCondition(cond, { runtime: "next", auth: "none", db: false, mobile: false });
|
|
69
75
|
const node = { cond, then: [], else: [] };
|
|
70
76
|
push(node);
|
|
71
77
|
stack.push({ node, inElse: false });
|
|
@@ -164,7 +170,7 @@ extension file.
|
|
|
164
170
|
|
|
165
171
|
\`qore-add-env-key\`, \`qore-add-integration\`, \`qore-add-connection\`,
|
|
166
172
|
\`qore-use-permissions\`, \`qore-observability\` and \`qore-use-database\`
|
|
167
|
-
produce code the portal reads: the
|
|
173
|
+
produce code the portal reads: the Variables tab, the Integrations tab,
|
|
168
174
|
connections, roles, Monitoring, the local database. An
|
|
169
175
|
extension may add to them but not relax them, and turning one off does not turn
|
|
170
176
|
off the SDK's lint rules that check the same things.
|
|
@@ -410,7 +416,7 @@ function renderReport(p, opts) {
|
|
|
410
416
|
const lines = [
|
|
411
417
|
"### Qore skills",
|
|
412
418
|
"",
|
|
413
|
-
`${opts.check ? "Out of date: `qore-skills sync` would update" : "Synced"} the managed skills for \`@quatronic/sdk@${p.manifest.sdkVersion}\` (runtime \`${f.runtime}\`, auth \`${f.auth}\`, database \`${f.db ? "yes" : "no"}\`${opts.inferred ? ", inferred from the app \u2014 pin with `qore-skills sync --features`" : ", pinned in the manifest"}).`
|
|
419
|
+
`${opts.check ? "Out of date: `qore-skills sync` would update" : "Synced"} the managed skills for \`@quatronic/sdk@${p.manifest.sdkVersion}\` (runtime \`${f.runtime}\`, auth \`${f.auth}\`, database \`${f.db ? "yes" : "no"}\`${f.mobile ? ", mobile app `yes`" : ""}${opts.inferred ? ", inferred from the app \u2014 pin with `qore-skills sync --features`" : ", pinned in the manifest"}).`
|
|
414
420
|
];
|
|
415
421
|
const managedWrites = [...p.writes.keys()].filter((r) => r !== MANIFEST_PATH);
|
|
416
422
|
if (!managedWrites.length && !p.deletes.length && p.claudeMd === void 0) {
|