@quatronic/sdk 0.10.1 → 0.11.0-test.014be98

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.
Files changed (90) hide show
  1. package/README.md +6 -0
  2. package/dist/chunk-BJN7YE63.js +46 -0
  3. package/dist/chunk-BJN7YE63.js.map +1 -0
  4. package/dist/{chunk-TPBRMW5N.js → chunk-GYUIIM5X.js} +35 -45
  5. package/dist/chunk-GYUIIM5X.js.map +1 -0
  6. package/dist/chunk-JM5LHJUJ.js +32 -0
  7. package/dist/chunk-JM5LHJUJ.js.map +1 -0
  8. package/dist/{chunk-YFZB5EW6.js → chunk-P5GBQVO7.js} +2 -2
  9. package/dist/chunk-S7TJQVXV.js +34 -0
  10. package/dist/chunk-S7TJQVXV.js.map +1 -0
  11. package/dist/{chunk-IFESUTF2.js → chunk-VQKYPW5V.js} +7 -3
  12. package/dist/chunk-VQKYPW5V.js.map +1 -0
  13. package/dist/{chunk-POZI4OKJ.js → chunk-WOFBDOMY.js} +2 -2
  14. package/dist/chunk-YJZZURE4.js +83 -0
  15. package/dist/chunk-YJZZURE4.js.map +1 -0
  16. package/dist/cli/skills-postinstall.js +13 -6
  17. package/dist/cli/skills.js +11 -5
  18. package/dist/context-CWvUIBHJ.d.ts +196 -0
  19. package/dist/eslint/index.d.ts +11 -1
  20. package/dist/eslint/index.js +123 -4
  21. package/dist/eslint/index.js.map +1 -1
  22. package/dist/expo/auth/index.d.ts +14 -0
  23. package/dist/expo/auth/index.js +324 -0
  24. package/dist/expo/auth/index.js.map +1 -0
  25. package/dist/expo/config/index.d.ts +38 -0
  26. package/dist/expo/config/index.js +35 -0
  27. package/dist/expo/config/index.js.map +1 -0
  28. package/dist/expo/log/index.d.ts +9 -0
  29. package/dist/expo/log/index.js +16 -0
  30. package/dist/expo/log/index.js.map +1 -0
  31. package/dist/expo/query/index.d.ts +41 -0
  32. package/dist/expo/query/index.js +98 -0
  33. package/dist/expo/query/index.js.map +1 -0
  34. package/dist/expo/sentry/index.d.ts +33 -0
  35. package/dist/expo/sentry/index.js +121 -0
  36. package/dist/expo/sentry/index.js.map +1 -0
  37. package/dist/expo/testing/index.d.ts +32 -0
  38. package/dist/expo/testing/index.js +58 -0
  39. package/dist/expo/testing/index.js.map +1 -0
  40. package/dist/expo/updates/index.d.ts +51 -0
  41. package/dist/expo/updates/index.js +163 -0
  42. package/dist/expo/updates/index.js.map +1 -0
  43. package/dist/next/auth/index.d.ts +50 -0
  44. package/dist/next/auth/index.js +524 -101
  45. package/dist/next/auth/index.js.map +1 -1
  46. package/dist/next/boot/index.js +3 -3
  47. package/dist/next/db/index.d.ts +3 -27
  48. package/dist/next/db/index.js +11 -30
  49. package/dist/next/db/index.js.map +1 -1
  50. package/dist/next/security/index.d.ts +24 -1
  51. package/dist/next/security/index.js +29 -0
  52. package/dist/next/security/index.js.map +1 -1
  53. package/dist/next/sentry/client.js +3 -3
  54. package/dist/next/sentry/client.js.map +1 -1
  55. package/dist/next/sentry/index.js +1 -1
  56. package/dist/next/sentry/register.js +3 -3
  57. package/dist/node/db/migrate/index.d.ts +28 -0
  58. package/dist/node/db/migrate/index.js +16 -0
  59. package/dist/node/db/migrate/index.js.map +1 -0
  60. package/dist/node/sentry/index.js +1 -1
  61. package/dist/node/sentry/register.js +2 -2
  62. package/package.json +89 -2
  63. package/skills/catalog.json +4 -1
  64. package/skills/qore-add-api-route/SKILL.md +1 -1
  65. package/skills/qore-add-connection/SKILL.next.md +3 -1
  66. package/skills/qore-add-connection/SKILL.node.md +3 -1
  67. package/skills/qore-add-env-key/SKILL.md +174 -9
  68. package/skills/qore-add-feature/SKILL.md +1 -1
  69. package/skills/qore-add-integration/SKILL.next.md +4 -2
  70. package/skills/qore-add-integration/SKILL.node.md +6 -6
  71. package/skills/qore-add-page/SKILL.md +1 -1
  72. package/skills/qore-author-skill/SKILL.md +1 -1
  73. package/skills/qore-debug-issue/SKILL.md +10 -0
  74. package/skills/qore-mobile-add-screen/SKILL.md +64 -0
  75. package/skills/qore-mobile-call-server/SKILL.md +75 -0
  76. package/skills/qore-mobile-run-on-device/SKILL.md +44 -0
  77. package/skills/qore-observability/SKILL.md +17 -0
  78. package/skills/qore-secure-io/SKILL.md +15 -0
  79. package/skills/qore-ship-checklist/SKILL.md +10 -0
  80. package/skills/qore-translate-strings/SKILL.md +10 -0
  81. package/skills/qore-use-addons/SKILL.md +2 -0
  82. package/skills/qore-use-database/SKILL.md +177 -147
  83. package/skills/qore-use-design-system/SKILL.md +1 -1
  84. package/skills/qore-use-mail-domain/SKILL.next.md +1 -1
  85. package/skills/qore-use-mail-domain/SKILL.node.md +2 -2
  86. package/skills/qore-use-permissions/SKILL.md +10 -0
  87. package/dist/chunk-IFESUTF2.js.map +0 -1
  88. package/dist/chunk-TPBRMW5N.js.map +0 -1
  89. /package/dist/{chunk-YFZB5EW6.js.map → chunk-P5GBQVO7.js.map} +0 -0
  90. /package/dist/{chunk-POZI4OKJ.js.map → chunk-WOFBDOMY.js.map} +0 -0
@@ -1,11 +1,11 @@
1
1
  import {
2
2
  onRequestError,
3
3
  register
4
- } from "../../chunk-POZI4OKJ.js";
5
- import "../../chunk-YFZB5EW6.js";
4
+ } from "../../chunk-WOFBDOMY.js";
5
+ import "../../chunk-P5GBQVO7.js";
6
6
  import "../../chunk-MET4SIMB.js";
7
7
  import "../../chunk-7ASQHY7O.js";
8
- import "../../chunk-IFESUTF2.js";
8
+ import "../../chunk-VQKYPW5V.js";
9
9
 
10
10
  // src/next/boot/index.ts
11
11
  async function qoreRegister(node) {
@@ -1,30 +1,6 @@
1
1
  export { PostgresConnectionConfig, PostgresSslConfig, isNorthflankManagedPostgres, resolvePostgresConfig } from '../../node/db/index.js';
2
- import { NodePgDatabase } from 'drizzle-orm/node-postgres';
3
-
4
- interface MigrationDb {
5
- readonly db: NodePgDatabase;
6
- readonly close: () => Promise<void>;
7
- }
8
- declare function createMigrationDb(databaseUrl: string): MigrationDb;
9
- declare function parseRoleFromUrl(databaseUrl: string): string;
10
- declare function grantRuntimeDefaultPrivileges(db: NodePgDatabase, schema: string, runtimeRole: string): Promise<void>;
11
-
12
- interface MigrateAppOptions {
13
- /** The Postgres schema the app's tables live in (`appSchema.schemaName`, or `"public"`). */
14
- schema: string;
15
- /** Defaults to `<cwd>/src/db/migrations`, where `pnpm db:generate` writes. */
16
- migrationsFolder?: string;
17
- /** The runtime role's DSN. Defaults to `DATABASE_URL`. */
18
- databaseUrl?: string;
19
- /** The migrator role's DSN. Defaults to `MIGRATION_DATABASE_URL`. */
20
- migrationDatabaseUrl?: string;
21
- }
22
- /**
23
- * Applies the app's drizzle-kit migrations as the migrator role, then grants
24
- * the runtime role access to what they created. Safe on every boot: drizzle
25
- * skips applied migrations and the grant is a no-op when both roles are one.
26
- */
27
- declare function migrateApp(options: MigrateAppOptions): Promise<void>;
2
+ export { MigrateAppOptions, MigrationDb, createMigrationDb, grantRuntimeDefaultPrivileges, migrateApp, parseRoleFromUrl } from '../../node/db/migrate/index.js';
3
+ import 'drizzle-orm/node-postgres';
28
4
 
29
5
  /**
30
6
  * The SDK's own auth-schema migrations (Keycloak apps), run as the migration
@@ -35,4 +11,4 @@ declare function migrateApp(options: MigrateAppOptions): Promise<void>;
35
11
  */
36
12
  declare function runQoreAuthMigrations(): Promise<void>;
37
13
 
38
- export { type MigrateAppOptions, type MigrationDb, createMigrationDb, grantRuntimeDefaultPrivileges, migrateApp, parseRoleFromUrl, runQoreAuthMigrations };
14
+ export { runQoreAuthMigrations };
@@ -1,48 +1,29 @@
1
+ import {
2
+ migrateApp
3
+ } from "../../chunk-S7TJQVXV.js";
4
+ import {
5
+ runAuthMigrations
6
+ } from "../../chunk-GYUIIM5X.js";
1
7
  import {
2
8
  createMigrationDb,
3
9
  grantRuntimeDefaultPrivileges,
4
- parseRoleFromUrl,
5
- runAuthMigrations
6
- } from "../../chunk-TPBRMW5N.js";
10
+ parseRoleFromUrl
11
+ } from "../../chunk-BJN7YE63.js";
7
12
  import {
8
13
  isNorthflankManagedPostgres,
9
14
  resolvePostgresConfig
10
15
  } from "../../chunk-4MBB2UQW.js";
11
16
 
12
- // src/db-core/migrate-app.ts
13
- import { join } from "path";
14
- import { migrate } from "drizzle-orm/node-postgres/migrator";
15
- function required(value, key) {
16
- if (!value) throw new Error(`migrateApp: ${key} is required`);
17
- return value;
18
- }
19
- async function migrateApp(options) {
20
- const databaseUrl = required(options.databaseUrl ?? process.env.DATABASE_URL, "DATABASE_URL");
21
- const migrationUrl = required(
22
- options.migrationDatabaseUrl ?? process.env.MIGRATION_DATABASE_URL,
23
- "MIGRATION_DATABASE_URL"
24
- );
25
- const { db, close } = createMigrationDb(migrationUrl);
26
- try {
27
- await migrate(db, {
28
- migrationsFolder: options.migrationsFolder ?? join(process.cwd(), "src/db/migrations")
29
- });
30
- await grantRuntimeDefaultPrivileges(db, options.schema, parseRoleFromUrl(databaseUrl));
31
- } finally {
32
- await close();
33
- }
34
- }
35
-
36
17
  // src/next/db/auth-migrations.ts
37
- function required2(key) {
18
+ function required(key) {
38
19
  const value = process.env[key];
39
20
  if (!value) throw new Error(`qoreRegister: ${key} is required`);
40
21
  return value;
41
22
  }
42
23
  async function runQoreAuthMigrations() {
43
- const { db, close } = createMigrationDb(required2("MIGRATION_DATABASE_URL"));
24
+ const { db, close } = createMigrationDb(required("MIGRATION_DATABASE_URL"));
44
25
  try {
45
- await runAuthMigrations(db, { runtimeRole: parseRoleFromUrl(required2("DATABASE_URL")) });
26
+ await runAuthMigrations(db, { runtimeRole: parseRoleFromUrl(required("DATABASE_URL")) });
46
27
  } finally {
47
28
  await close();
48
29
  }
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/db-core/migrate-app.ts","../../../src/next/db/auth-migrations.ts"],"sourcesContent":["import { join } from \"node:path\"\nimport { migrate } from \"drizzle-orm/node-postgres/migrator\"\nimport { createMigrationDb, grantRuntimeDefaultPrivileges, parseRoleFromUrl } from \"./migration-db\"\n\nexport interface MigrateAppOptions {\n /** The Postgres schema the app's tables live in (`appSchema.schemaName`, or `\"public\"`). */\n schema: string\n /** Defaults to `<cwd>/src/db/migrations`, where `pnpm db:generate` writes. */\n migrationsFolder?: string\n /** The runtime role's DSN. Defaults to `DATABASE_URL`. */\n databaseUrl?: string\n /** The migrator role's DSN. Defaults to `MIGRATION_DATABASE_URL`. */\n migrationDatabaseUrl?: string\n}\n\nfunction required(value: string | undefined, key: string): string {\n if (!value) throw new Error(`migrateApp: ${key} is required`)\n return value\n}\n\n/**\n * Applies the app's drizzle-kit migrations as the migrator role, then grants\n * the runtime role access to what they created. Safe on every boot: drizzle\n * skips applied migrations and the grant is a no-op when both roles are one.\n */\nexport async function migrateApp(options: MigrateAppOptions): Promise<void> {\n const databaseUrl = required(options.databaseUrl ?? process.env.DATABASE_URL, \"DATABASE_URL\")\n const migrationUrl = required(\n options.migrationDatabaseUrl ?? process.env.MIGRATION_DATABASE_URL,\n \"MIGRATION_DATABASE_URL\",\n )\n const { db, close } = createMigrationDb(migrationUrl)\n try {\n await migrate(db, {\n migrationsFolder: options.migrationsFolder ?? join(process.cwd(), \"src/db/migrations\"),\n })\n await grantRuntimeDefaultPrivileges(db, options.schema, parseRoleFromUrl(databaseUrl))\n } finally {\n await close()\n }\n}\n","import { runAuthMigrations } from \"../../auth-core/migrate\"\nimport { createMigrationDb, parseRoleFromUrl } from \"../../db-core/migration-db\"\n\nfunction required(key: string): string {\n const value = process.env[key]\n if (!value) throw new Error(`qoreRegister: ${key} is required`)\n return value\n}\n\n/**\n * The SDK's own auth-schema migrations (Keycloak apps), run as the migration\n * role from `MIGRATION_DATABASE_URL`, granting the runtime role from\n * `DATABASE_URL`. `qoreRegister` calls it through\n * `authMigrations: () => import(\"@quatronic/sdk/next/db\")`, so an app without a\n * database never bundles pg or drizzle.\n */\nexport async function runQoreAuthMigrations(): Promise<void> {\n const { db, close } = createMigrationDb(required(\"MIGRATION_DATABASE_URL\"))\n try {\n await runAuthMigrations(db, { runtimeRole: parseRoleFromUrl(required(\"DATABASE_URL\")) })\n } finally {\n await close()\n }\n}\n"],"mappings":";;;;;;;;;;;;AAAA,SAAS,YAAY;AACrB,SAAS,eAAe;AAcxB,SAAS,SAAS,OAA2B,KAAqB;AAChE,MAAI,CAAC,MAAO,OAAM,IAAI,MAAM,eAAe,GAAG,cAAc;AAC5D,SAAO;AACT;AAOA,eAAsB,WAAW,SAA2C;AAC1E,QAAM,cAAc,SAAS,QAAQ,eAAe,QAAQ,IAAI,cAAc,cAAc;AAC5F,QAAM,eAAe;AAAA,IACnB,QAAQ,wBAAwB,QAAQ,IAAI;AAAA,IAC5C;AAAA,EACF;AACA,QAAM,EAAE,IAAI,MAAM,IAAI,kBAAkB,YAAY;AACpD,MAAI;AACF,UAAM,QAAQ,IAAI;AAAA,MAChB,kBAAkB,QAAQ,oBAAoB,KAAK,QAAQ,IAAI,GAAG,mBAAmB;AAAA,IACvF,CAAC;AACD,UAAM,8BAA8B,IAAI,QAAQ,QAAQ,iBAAiB,WAAW,CAAC;AAAA,EACvF,UAAE;AACA,UAAM,MAAM;AAAA,EACd;AACF;;;ACrCA,SAASA,UAAS,KAAqB;AACrC,QAAM,QAAQ,QAAQ,IAAI,GAAG;AAC7B,MAAI,CAAC,MAAO,OAAM,IAAI,MAAM,iBAAiB,GAAG,cAAc;AAC9D,SAAO;AACT;AASA,eAAsB,wBAAuC;AAC3D,QAAM,EAAE,IAAI,MAAM,IAAI,kBAAkBA,UAAS,wBAAwB,CAAC;AAC1E,MAAI;AACF,UAAM,kBAAkB,IAAI,EAAE,aAAa,iBAAiBA,UAAS,cAAc,CAAC,EAAE,CAAC;AAAA,EACzF,UAAE;AACA,UAAM,MAAM;AAAA,EACd;AACF;","names":["required"]}
1
+ {"version":3,"sources":["../../../src/next/db/auth-migrations.ts"],"sourcesContent":["import { runAuthMigrations } from \"../../auth-core/migrate\"\nimport { createMigrationDb, parseRoleFromUrl } from \"../../db-core/migration-db\"\n\nfunction required(key: string): string {\n const value = process.env[key]\n if (!value) throw new Error(`qoreRegister: ${key} is required`)\n return value\n}\n\n/**\n * The SDK's own auth-schema migrations (Keycloak apps), run as the migration\n * role from `MIGRATION_DATABASE_URL`, granting the runtime role from\n * `DATABASE_URL`. `qoreRegister` calls it through\n * `authMigrations: () => import(\"@quatronic/sdk/next/db\")`, so an app without a\n * database never bundles pg or drizzle.\n */\nexport async function runQoreAuthMigrations(): Promise<void> {\n const { db, close } = createMigrationDb(required(\"MIGRATION_DATABASE_URL\"))\n try {\n await runAuthMigrations(db, { runtimeRole: parseRoleFromUrl(required(\"DATABASE_URL\")) })\n } finally {\n await close()\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAGA,SAAS,SAAS,KAAqB;AACrC,QAAM,QAAQ,QAAQ,IAAI,GAAG;AAC7B,MAAI,CAAC,MAAO,OAAM,IAAI,MAAM,iBAAiB,GAAG,cAAc;AAC9D,SAAO;AACT;AASA,eAAsB,wBAAuC;AAC3D,QAAM,EAAE,IAAI,MAAM,IAAI,kBAAkB,SAAS,wBAAwB,CAAC;AAC1E,MAAI;AACF,UAAM,kBAAkB,IAAI,EAAE,aAAa,iBAAiB,SAAS,cAAc,CAAC,EAAE,CAAC;AAAA,EACzF,UAAE;AACA,UAAM,MAAM;AAAA,EACd;AACF;","names":[]}
@@ -127,6 +127,29 @@ interface QoreProxyOptions {
127
127
  */
128
128
  declare function qoreProxy(options?: QoreProxyOptions): SecuredProxy;
129
129
 
130
+ declare const API_LEVEL_HEADER = "x-qore-api-level";
131
+ interface MobileApiLevels {
132
+ /** The API level this server speaks. */
133
+ apiLevel: number;
134
+ /** The oldest phone build's level this server still serves. */
135
+ minApiLevel: number;
136
+ }
137
+ /**
138
+ * 426 for a phone build below `minApiLevel`, else `null`. A request without
139
+ * the header passes: the web pages call the same routes, and a build from
140
+ * before the contract cannot be told apart from them. A header that is not an
141
+ * integer counts as level 0.
142
+ */
143
+ declare function requireMobileApiLevel(req: Request, minApiLevel: number): Response | null;
144
+ /**
145
+ * The app's `src/app/api/qore/app-version/route.ts`: a public GET that tells a
146
+ * phone whether its build is still served. Throws at import when the levels
147
+ * contradict each other, so a bad edit fails the build rather than a device.
148
+ */
149
+ declare function createAppVersionRoute(levels: MobileApiLevels): {
150
+ GET: () => Response;
151
+ };
152
+
130
153
  /**
131
154
  * What a Next proxy (formerly "middleware") is allowed to be.
132
155
  *
@@ -173,4 +196,4 @@ declare const NONCE_HEADER = "x-qdc-nonce";
173
196
  */
174
197
  declare function withSecurityHeaders(handler: ProxyHandlerFn, options?: SecurityHeaderOptions): SecuredProxy;
175
198
 
176
- export { type CspReportFields, type CspReportLogger, type CspReportRouteOptions, NONCE_HEADER, type ProxyHandlerFn, QORE_CSP_REPORT_URI, type QoreProxyAuth, type QoreProxyOptions, STATIC_SECURITY_HEADERS, type SecuredProxy, type SecurityHeaderOptions, buildCsp, createCspReportRoute, proxyMatcher, qoreProxy, readCspReport, withSecurityHeaders };
199
+ export { API_LEVEL_HEADER, type CspReportFields, type CspReportLogger, type CspReportRouteOptions, type MobileApiLevels, NONCE_HEADER, type ProxyHandlerFn, QORE_CSP_REPORT_URI, type QoreProxyAuth, type QoreProxyOptions, STATIC_SECURITY_HEADERS, type SecuredProxy, type SecurityHeaderOptions, buildCsp, createAppVersionRoute, createCspReportRoute, proxyMatcher, qoreProxy, readCspReport, requireMobileApiLevel, withSecurityHeaders };
@@ -99,6 +99,32 @@ function qoreProxy(options = {}) {
99
99
  );
100
100
  }
101
101
 
102
+ // src/next/security/apiLevel.ts
103
+ var API_LEVEL_HEADER = "x-qore-api-level";
104
+ function assertLevels({ apiLevel, minApiLevel }) {
105
+ for (const [name, v] of [["apiLevel", apiLevel], ["minApiLevel", minApiLevel]]) {
106
+ if (!Number.isInteger(v) || v < 0) throw new Error(`${name} must be a non-negative integer, got ${v}`);
107
+ }
108
+ if (minApiLevel > apiLevel) throw new Error(`minApiLevel (${minApiLevel}) is above apiLevel (${apiLevel})`);
109
+ }
110
+ function requireMobileApiLevel(req, minApiLevel) {
111
+ const raw = req.headers.get(API_LEVEL_HEADER);
112
+ if (raw === null) return null;
113
+ const level = /^\d{1,6}$/.test(raw.trim()) ? Number(raw.trim()) : 0;
114
+ if (level >= minApiLevel) return null;
115
+ return Response.json(
116
+ { error: "upgrade_required", minApiLevel },
117
+ { status: 426, headers: { "cache-control": "no-store" } }
118
+ );
119
+ }
120
+ function createAppVersionRoute(levels) {
121
+ assertLevels(levels);
122
+ const body = { apiLevel: levels.apiLevel, minApiLevel: levels.minApiLevel };
123
+ return {
124
+ GET: () => Response.json(body, { headers: { "cache-control": "no-store" } })
125
+ };
126
+ }
127
+
102
128
  // src/next/security/index.ts
103
129
  var NONCE_BYTES = 16;
104
130
  var NONCE_HEADER = "x-qdc-nonce";
@@ -151,14 +177,17 @@ function withSecurityHeaders(handler, options = {}) {
151
177
  };
152
178
  }
153
179
  export {
180
+ API_LEVEL_HEADER,
154
181
  NONCE_HEADER,
155
182
  QORE_CSP_REPORT_URI,
156
183
  STATIC_SECURITY_HEADERS,
157
184
  buildCsp,
185
+ createAppVersionRoute,
158
186
  createCspReportRoute,
159
187
  proxyMatcher,
160
188
  qoreProxy,
161
189
  readCspReport,
190
+ requireMobileApiLevel,
162
191
  withSecurityHeaders
163
192
  };
164
193
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/next/security/index.ts","../../../src/security-core/csp.ts","../../../src/next/security/qoreProxy.ts"],"sourcesContent":["import { NextResponse } from \"next/server\"\nimport type { NextFetchEvent, NextRequest } from \"next/server\"\n\nimport { buildCsp, cspHeaderName, type SecurityHeaderOptions } from \"../../security-core/csp\"\nimport { STATIC_SECURITY_HEADERS } from \"../../security-core/headers\"\n\nexport { buildCsp } from \"../../security-core/csp\"\nexport type { SecurityHeaderOptions } from \"../../security-core/csp\"\nexport { STATIC_SECURITY_HEADERS } from \"../../security-core/headers\"\nexport { proxyMatcher } from \"../../security-core/proxy\"\nexport { createCspReportRoute, readCspReport, QORE_CSP_REPORT_URI } from \"../../security-core/cspReport\"\nexport { qoreProxy } from \"./qoreProxy\"\nexport type { QoreProxyAuth, QoreProxyOptions } from \"./qoreProxy\"\nexport type {\n CspReportFields,\n CspReportLogger,\n CspReportRouteOptions,\n} from \"../../security-core/cspReport\"\n\n/**\n * What a Next proxy (formerly \"middleware\") is allowed to be.\n *\n * Named `ProxyHandlerFn` rather than `ProxyHandler` because `ProxyHandler<T>`\n * is a TypeScript lib global — exporting that name would shadow it in every\n * file that imports from this entry point.\n *\n * Returning nothing means \"pass through\", and that is the shape to prefer: it\n * lets `withSecurityHeaders` build the pass-through response itself, which is\n * the only way the nonce reaches the renderer (see below).\n */\nexport type ProxyHandlerFn = (\n request: NextRequest,\n event: NextFetchEvent,\n) => Response | undefined | null | Promise<Response | undefined | null>\n\n/**\n * What `withSecurityHeaders` returns: the full Next proxy signature, rather\n * than the handler's own. The wrapper genuinely accepts both arguments and\n * genuinely always resolves to a `Response` — a handler that returns nothing\n * still comes back as a pass-through. Next accepts this shape as a `proxy`\n * export unchanged.\n *\n * Named because `@quatronic/sdk/next/security/testing` takes one.\n */\nexport type SecuredProxy = (request: NextRequest, event: NextFetchEvent) => Promise<Response>\n\n/** 128 bits, the CSP spec's floor. */\nconst NONCE_BYTES = 16\n\n/** The header app code reads to nonce its own inline script or style. */\nexport const NONCE_HEADER = \"x-qdc-nonce\"\n\nfunction generateNonce(): string {\n // `crypto.getRandomValues`, not `randomUUID()`: a UUID is 122 bits of\n // randomness wearing a fixed-format costume, and `randomUUID` is absent from\n // some edge runtimes. Web Crypto is present in both edge and node.\n const bytes = new Uint8Array(NONCE_BYTES)\n crypto.getRandomValues(bytes)\n let binary = \"\"\n for (const byte of bytes) binary += String.fromCharCode(byte)\n return btoa(binary)\n}\n\nfunction isPassThrough(response: Response): boolean {\n // How `NextResponse.next()` marks itself. Reading it is a dependency on a\n // Next internal, so it is the *fallback* path only — a handler that returns\n // nothing never reaches here. If Next ever renames the marker the cost is a\n // response that carries the headers but not the request-side nonce, which is\n // exactly what we would have had without this branch.\n return response.headers.get(\"x-middleware-next\") === \"1\"\n}\n\nfunction carryOver(from: Response, to: Response): void {\n from.headers.forEach((value, key) => {\n // `x-middleware-*` is Next's own pass-through plumbing, including the\n // encoding of the forwarded request headers. The fresh response regenerates\n // all of it; copying the stale copy over would undo the nonce we just set.\n if (key.toLowerCase().startsWith(\"x-middleware-\")) return\n if (key.toLowerCase() === \"set-cookie\") return\n to.headers.set(key, value)\n })\n // `forEach` folds multiple Set-Cookie headers into one comma-joined string,\n // which no browser parses back into two cookies. `getSetCookie` is the only\n // accessor that keeps them separate.\n for (const cookie of from.headers.getSetCookie?.() ?? []) {\n to.headers.append(\"set-cookie\", cookie)\n }\n}\n\nfunction applySecurityHeaders(response: Response, cspName: string, csp: string): void {\n for (const [name, value] of STATIC_SECURITY_HEADERS) {\n response.headers.set(name, value)\n }\n response.headers.set(cspName, csp)\n}\n\n/**\n * Wrap a Next proxy so every response it produces carries the QDC security\n * headers and a per-response CSP nonce.\n *\n * The nonce goes on the **request** headers under two names: `x-qdc-nonce` for\n * app code, and `Content-Security-Policy` because that is where Next itself\n * looks for it. Next parses the request's CSP header, extracts `nonce-…`, and\n * stamps that nonce onto the bootstrap `<script>` tags it emits. Without it,\n * every generated app breaks the moment `script-src` stops allowing\n * `'unsafe-inline'`.\n *\n * A nonce is per response. Any route whose HTML carries one must render\n * dynamically and must not be cached by a CDN, or every visitor shares a single\n * nonce and the nonce protects nothing.\n *\n * The return type is the full proxy signature rather than the handler's own,\n * because the wrapper genuinely does accept both arguments and genuinely always\n * resolves to a `Response` — a handler that returns nothing still comes back as\n * a pass-through. Next accepts this shape as a `proxy` export unchanged.\n */\nexport function withSecurityHeaders(\n handler: ProxyHandlerFn,\n options: SecurityHeaderOptions = {},\n): SecuredProxy {\n return async (request: NextRequest, event: NextFetchEvent): Promise<Response> => {\n const nonce = generateNonce()\n const csp = buildCsp(nonce, { ...options, sentryDsn: options.sentryDsn ?? process.env.SENTRY_DSN })\n const cspName = cspHeaderName(options)\n\n const requestHeaders = new Headers(request.headers)\n requestHeaders.set(NONCE_HEADER, nonce)\n // Always the enforcing name on the request, even in report-only mode: this\n // copy is how Next finds the nonce, not a policy the browser ever sees.\n requestHeaders.set(\"content-security-policy\", csp)\n\n const handled = await handler(request, event)\n\n let response: Response\n if (!handled) {\n response = NextResponse.next({ request: { headers: requestHeaders } })\n } else if (isPassThrough(handled)) {\n response = NextResponse.next({ request: { headers: requestHeaders } })\n carryOver(handled, response)\n } else {\n // A redirect or an early 401. It never reaches a Next route, so the\n // build-time `headers()` set in `withQdcConfig` would miss it — which is\n // precisely why the headers are applied here too.\n response = handled\n }\n\n applySecurityHeaders(response, cspName, csp)\n return response\n }\n}\n","// Content-Security-Policy assembly. Pure string work, no `next` and no Node\n// built-ins, so the edge proxy can call it.\n\n/** Options for the security headers a QDC app sends on every response. */\nexport interface SecurityHeaderOptions {\n /**\n * Who may frame this app. Defaults to `[\"'none'\"]` — nobody. Values are\n * CSP source expressions, so quoted keywords keep their quotes.\n */\n frameAncestors?: string[]\n /**\n * What this app may frame, on top of `'self'`. Defaults to `[\"'self'\"]`.\n *\n * Without an explicit `frame-src` the directive falls through to\n * `default-src 'self'`, so an app could embed nothing at all — no payment\n * iframe, no map, no video. That was a gap rather than a decision, so the\n * directive is written out and an app widens it here.\n *\n * This is the opposite direction from `frameAncestors`: that one says who may\n * embed us, this one says what we may embed.\n */\n frameSrc?: string[]\n /**\n * Extra origins the browser may open connections to, on top of `'self'`.\n * In a generated app these are the origins behind its `CONN_*` secrets.\n */\n connectSrc?: string[]\n /** Where the browser posts violation reports. Defaults to `/api/csp-report`. */\n reportUri?: string\n /**\n * Send `Content-Security-Policy-Report-Only` instead of the enforcing\n * header. **Defaults to `true`.**\n *\n * `'strict-dynamic'` makes the browser ignore `'self'` and every host\n * allow-list for scripts, so a policy that is slightly wrong is a blank page\n * in production rather than a degraded one. Enforcing before the reports have\n * been read gets the whole policy reverted instead of tightened, so Stage 1\n * collects evidence at `/api/csp-report` first. Pass `false` once those\n * reports are clean for your app.\n */\n reportOnly?: boolean\n /** DSN whose ingest origin the browser may post to. */\n sentryDsn?: string\n}\n\n// Only http(s) has a meaningful `origin` — a DSN with some other scheme (or\n// no scheme at all) gives `URL.origin === \"null\"`, which would otherwise\n// become a literal \"null\" token in connect-src.\nconst HTTP_PROTOCOLS = new Set([\"http:\", \"https:\"])\n\n/** The origin a browser-side Sentry SDK for this DSN posts events to, or `undefined` for an absent/malformed DSN. */\nexport function sentryIngestOrigin(dsn: string | undefined): string | undefined {\n if (!dsn) return undefined\n try {\n const url = new URL(dsn)\n return HTTP_PROTOCOLS.has(url.protocol) ? url.origin : undefined\n } catch {\n return undefined\n }\n}\n\n// A source expression containing \";\" or a newline would end the directive and\n// start a new one — i.e. let caller-supplied config rewrite the whole policy.\n// Reject rather than strip: a silently mangled origin is a connect-src that\n// quietly fails at runtime.\nconst UNSAFE_IN_DIRECTIVE = /[;\\r\\n]/\n\nfunction assertSafe(kind: string, values: readonly string[]): void {\n for (const value of values) {\n if (UNSAFE_IN_DIRECTIVE.test(value)) {\n throw new Error(`Invalid ${kind} for CSP: ${JSON.stringify(value)} contains \";\" or a newline`)\n }\n }\n}\n\n/**\n * Build the Stage-1 QDC policy for one response.\n *\n * `script-src` carries the per-response nonce plus `'strict-dynamic'`, so a\n * script the app itself marked may load further scripts and nothing else runs.\n * `style-src` deliberately keeps `'unsafe-inline'`: HeroUI and Tailwind emit\n * inline styles, and removing it in the same change that introduces the policy\n * would break every generated app — Stage 2 replaces it with the nonce after\n * its own styling audit.\n */\nexport function buildCsp(nonce: string, options: SecurityHeaderOptions = {}): string {\n const frameAncestors = options.frameAncestors ?? [\"'none'\"]\n const frameSrc = options.frameSrc ?? [\"'self'\"]\n const connectSrc = options.connectSrc ?? []\n const reportUri = options.reportUri ?? \"/api/csp-report\"\n const sentryOrigin = sentryIngestOrigin(options.sentryDsn)\n\n assertSafe(\"nonce\", [nonce])\n assertSafe(\"frameAncestors entry\", frameAncestors)\n assertSafe(\"frameSrc entry\", frameSrc)\n assertSafe(\"connectSrc entry\", connectSrc)\n assertSafe(\"reportUri\", [reportUri])\n if (sentryOrigin) assertSafe(\"sentryDsn origin\", [sentryOrigin])\n\n const directives = [\n \"default-src 'self'\",\n `script-src 'self' 'nonce-${nonce}' 'strict-dynamic'`,\n \"style-src 'self' 'unsafe-inline'\",\n \"img-src 'self' data: blob: https:\",\n \"font-src 'self' data:\",\n \"worker-src 'self' blob:\",\n [\"connect-src\", \"'self'\", ...connectSrc, ...(sentryOrigin ? [sentryOrigin] : [])].join(\" \"),\n ...(frameSrc.length > 0 ? [[\"frame-src\", ...frameSrc].join(\" \")] : [\"frame-src 'none'\"]),\n ...(frameAncestors.length > 0 ? [[\"frame-ancestors\", ...frameAncestors].join(\" \")] : []),\n \"base-uri 'self'\",\n \"form-action 'self'\",\n \"object-src 'none'\",\n \"upgrade-insecure-requests\",\n ...(reportUri ? [`report-uri ${reportUri}`] : []),\n ]\n\n return directives.join(\"; \") + \";\"\n}\n\n/** The header name matching `options.reportOnly`. */\nexport function cspHeaderName(options: SecurityHeaderOptions = {}): string {\n return (options.reportOnly ?? true)\n ? \"Content-Security-Policy-Report-Only\"\n : \"Content-Security-Policy\"\n}\n","import { NextResponse } from \"next/server\"\nimport type { NextRequest } from \"next/server\"\n\nimport type { SecurityHeaderOptions } from \"../../security-core/csp\"\nimport { QORE_CSP_REPORT_URI } from \"../../security-core/cspReport\"\nimport { withSecurityHeaders, type ProxyHandlerFn, type SecuredProxy } from \"./index\"\n\nexport type QoreProxyAuth = \"keycloak\" | \"betterauth\" | \"none\"\n\nexport interface QoreProxyOptions {\n /** Which session the proxy pre-checks. Real validation stays server-side. */\n auth?: QoreProxyAuth\n /** Overrides for the security headers and the CSP. */\n security?: SecurityHeaderOptions\n /**\n * The app's own proxy logic. Runs after the session pre-check passes;\n * return nothing to pass through, or a Response to answer early.\n */\n handler?: ProxyHandlerFn\n}\n\n\n// Kept equal to auth-core's COOKIE_NAME by a test; imported from there it would\n// pull the session module into every proxy bundle.\nconst KEYCLOAK_SESSION_COOKIE = \"qdc_session\"\nconst BETTERAUTH_SESSION_SUFFIX = \"better-auth.session_token\"\n\nfunction keycloakGate(req: NextRequest): Response | undefined {\n if (req.cookies.has(KEYCLOAK_SESSION_COOKIE)) return undefined\n const url = req.nextUrl.clone()\n url.pathname = \"/api/auth/login\"\n url.search = \"\"\n url.searchParams.set(\"redirect\", req.nextUrl.pathname + req.nextUrl.search)\n return NextResponse.redirect(url)\n}\n\nfunction betterAuthGate(req: NextRequest): Response | undefined {\n if (req.cookies.getAll().some((c) => c.name.endsWith(BETTERAUTH_SESSION_SUFFIX))) return undefined\n const url = req.nextUrl.clone()\n url.pathname = \"/login\"\n return NextResponse.redirect(url)\n}\n\nconst GATES: Record<QoreProxyAuth, ((req: NextRequest) => Response | undefined) | null> = {\n keycloak: keycloakGate,\n betterauth: betterAuthGate,\n none: null,\n}\n\n/**\n * The body of a Next app's `src/proxy.ts`: security headers and a CSP nonce on\n * every response, a cheap session-cookie pre-check that redirects to login,\n * then the app's own handler. Which paths it covers stays the app's `config`\n * literal, since Next reads that statically.\n */\nexport function qoreProxy(options: QoreProxyOptions = {}): SecuredProxy {\n const gate = GATES[options.auth ?? \"none\"]\n const handler = options.handler\n return withSecurityHeaders(\n async (req, event) => gate?.(req) ?? (handler ? handler(req, event) : undefined),\n { reportUri: QORE_CSP_REPORT_URI, ...options.security },\n )\n}\n"],"mappings":";;;;;;;;;;;;;;AAAA,SAAS,gBAAAA,qBAAoB;;;ACgD7B,IAAM,iBAAiB,oBAAI,IAAI,CAAC,SAAS,QAAQ,CAAC;AAG3C,SAAS,mBAAmB,KAA6C;AAC9E,MAAI,CAAC,IAAK,QAAO;AACjB,MAAI;AACF,UAAM,MAAM,IAAI,IAAI,GAAG;AACvB,WAAO,eAAe,IAAI,IAAI,QAAQ,IAAI,IAAI,SAAS;AAAA,EACzD,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAMA,IAAM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AAU,SAAS,GAAG;AAC3C,WAAO;AAAA,EACT;AACF;","names":["NextResponse","NextResponse"]}
1
+ {"version":3,"sources":["../../../src/next/security/index.ts","../../../src/security-core/csp.ts","../../../src/next/security/qoreProxy.ts","../../../src/next/security/apiLevel.ts"],"sourcesContent":["import { NextResponse } from \"next/server\"\nimport type { NextFetchEvent, NextRequest } from \"next/server\"\n\nimport { buildCsp, cspHeaderName, type SecurityHeaderOptions } from \"../../security-core/csp\"\nimport { STATIC_SECURITY_HEADERS } from \"../../security-core/headers\"\n\nexport { buildCsp } from \"../../security-core/csp\"\nexport type { SecurityHeaderOptions } from \"../../security-core/csp\"\nexport { STATIC_SECURITY_HEADERS } from \"../../security-core/headers\"\nexport { proxyMatcher } from \"../../security-core/proxy\"\nexport { createCspReportRoute, readCspReport, QORE_CSP_REPORT_URI } from \"../../security-core/cspReport\"\nexport { qoreProxy } from \"./qoreProxy\"\nexport { API_LEVEL_HEADER, createAppVersionRoute, requireMobileApiLevel } from \"./apiLevel\"\nexport type { MobileApiLevels } from \"./apiLevel\"\nexport type { QoreProxyAuth, QoreProxyOptions } from \"./qoreProxy\"\nexport type {\n CspReportFields,\n CspReportLogger,\n CspReportRouteOptions,\n} from \"../../security-core/cspReport\"\n\n/**\n * What a Next proxy (formerly \"middleware\") is allowed to be.\n *\n * Named `ProxyHandlerFn` rather than `ProxyHandler` because `ProxyHandler<T>`\n * is a TypeScript lib global — exporting that name would shadow it in every\n * file that imports from this entry point.\n *\n * Returning nothing means \"pass through\", and that is the shape to prefer: it\n * lets `withSecurityHeaders` build the pass-through response itself, which is\n * the only way the nonce reaches the renderer (see below).\n */\nexport type ProxyHandlerFn = (\n request: NextRequest,\n event: NextFetchEvent,\n) => Response | undefined | null | Promise<Response | undefined | null>\n\n/**\n * What `withSecurityHeaders` returns: the full Next proxy signature, rather\n * than the handler's own. The wrapper genuinely accepts both arguments and\n * genuinely always resolves to a `Response` — a handler that returns nothing\n * still comes back as a pass-through. Next accepts this shape as a `proxy`\n * export unchanged.\n *\n * Named because `@quatronic/sdk/next/security/testing` takes one.\n */\nexport type SecuredProxy = (request: NextRequest, event: NextFetchEvent) => Promise<Response>\n\n/** 128 bits, the CSP spec's floor. */\nconst NONCE_BYTES = 16\n\n/** The header app code reads to nonce its own inline script or style. */\nexport const NONCE_HEADER = \"x-qdc-nonce\"\n\nfunction generateNonce(): string {\n // `crypto.getRandomValues`, not `randomUUID()`: a UUID is 122 bits of\n // randomness wearing a fixed-format costume, and `randomUUID` is absent from\n // some edge runtimes. Web Crypto is present in both edge and node.\n const bytes = new Uint8Array(NONCE_BYTES)\n crypto.getRandomValues(bytes)\n let binary = \"\"\n for (const byte of bytes) binary += String.fromCharCode(byte)\n return btoa(binary)\n}\n\nfunction isPassThrough(response: Response): boolean {\n // How `NextResponse.next()` marks itself. Reading it is a dependency on a\n // Next internal, so it is the *fallback* path only — a handler that returns\n // nothing never reaches here. If Next ever renames the marker the cost is a\n // response that carries the headers but not the request-side nonce, which is\n // exactly what we would have had without this branch.\n return response.headers.get(\"x-middleware-next\") === \"1\"\n}\n\nfunction carryOver(from: Response, to: Response): void {\n from.headers.forEach((value, key) => {\n // `x-middleware-*` is Next's own pass-through plumbing, including the\n // encoding of the forwarded request headers. The fresh response regenerates\n // all of it; copying the stale copy over would undo the nonce we just set.\n if (key.toLowerCase().startsWith(\"x-middleware-\")) return\n if (key.toLowerCase() === \"set-cookie\") return\n to.headers.set(key, value)\n })\n // `forEach` folds multiple Set-Cookie headers into one comma-joined string,\n // which no browser parses back into two cookies. `getSetCookie` is the only\n // accessor that keeps them separate.\n for (const cookie of from.headers.getSetCookie?.() ?? []) {\n to.headers.append(\"set-cookie\", cookie)\n }\n}\n\nfunction applySecurityHeaders(response: Response, cspName: string, csp: string): void {\n for (const [name, value] of STATIC_SECURITY_HEADERS) {\n response.headers.set(name, value)\n }\n response.headers.set(cspName, csp)\n}\n\n/**\n * Wrap a Next proxy so every response it produces carries the QDC security\n * headers and a per-response CSP nonce.\n *\n * The nonce goes on the **request** headers under two names: `x-qdc-nonce` for\n * app code, and `Content-Security-Policy` because that is where Next itself\n * looks for it. Next parses the request's CSP header, extracts `nonce-…`, and\n * stamps that nonce onto the bootstrap `<script>` tags it emits. Without it,\n * every generated app breaks the moment `script-src` stops allowing\n * `'unsafe-inline'`.\n *\n * A nonce is per response. Any route whose HTML carries one must render\n * dynamically and must not be cached by a CDN, or every visitor shares a single\n * nonce and the nonce protects nothing.\n *\n * The return type is the full proxy signature rather than the handler's own,\n * because the wrapper genuinely does accept both arguments and genuinely always\n * resolves to a `Response` — a handler that returns nothing still comes back as\n * a pass-through. Next accepts this shape as a `proxy` export unchanged.\n */\nexport function withSecurityHeaders(\n handler: ProxyHandlerFn,\n options: SecurityHeaderOptions = {},\n): SecuredProxy {\n return async (request: NextRequest, event: NextFetchEvent): Promise<Response> => {\n const nonce = generateNonce()\n const csp = buildCsp(nonce, { ...options, sentryDsn: options.sentryDsn ?? process.env.SENTRY_DSN })\n const cspName = cspHeaderName(options)\n\n const requestHeaders = new Headers(request.headers)\n requestHeaders.set(NONCE_HEADER, nonce)\n // Always the enforcing name on the request, even in report-only mode: this\n // copy is how Next finds the nonce, not a policy the browser ever sees.\n requestHeaders.set(\"content-security-policy\", csp)\n\n const handled = await handler(request, event)\n\n let response: Response\n if (!handled) {\n response = NextResponse.next({ request: { headers: requestHeaders } })\n } else if (isPassThrough(handled)) {\n response = NextResponse.next({ request: { headers: requestHeaders } })\n carryOver(handled, response)\n } else {\n // A redirect or an early 401. It never reaches a Next route, so the\n // build-time `headers()` set in `withQdcConfig` would miss it — which is\n // precisely why the headers are applied here too.\n response = handled\n }\n\n applySecurityHeaders(response, cspName, csp)\n return response\n }\n}\n","// Content-Security-Policy assembly. Pure string work, no `next` and no Node\n// built-ins, so the edge proxy can call it.\n\n/** Options for the security headers a QDC app sends on every response. */\nexport interface SecurityHeaderOptions {\n /**\n * Who may frame this app. Defaults to `[\"'none'\"]` — nobody. Values are\n * CSP source expressions, so quoted keywords keep their quotes.\n */\n frameAncestors?: string[]\n /**\n * What this app may frame, on top of `'self'`. Defaults to `[\"'self'\"]`.\n *\n * Without an explicit `frame-src` the directive falls through to\n * `default-src 'self'`, so an app could embed nothing at all — no payment\n * iframe, no map, no video. That was a gap rather than a decision, so the\n * directive is written out and an app widens it here.\n *\n * This is the opposite direction from `frameAncestors`: that one says who may\n * embed us, this one says what we may embed.\n */\n frameSrc?: string[]\n /**\n * Extra origins the browser may open connections to, on top of `'self'`.\n * In a generated app these are the origins behind its `CONN_*` secrets.\n */\n connectSrc?: string[]\n /** Where the browser posts violation reports. Defaults to `/api/csp-report`. */\n reportUri?: string\n /**\n * Send `Content-Security-Policy-Report-Only` instead of the enforcing\n * header. **Defaults to `true`.**\n *\n * `'strict-dynamic'` makes the browser ignore `'self'` and every host\n * allow-list for scripts, so a policy that is slightly wrong is a blank page\n * in production rather than a degraded one. Enforcing before the reports have\n * been read gets the whole policy reverted instead of tightened, so Stage 1\n * collects evidence at `/api/csp-report` first. Pass `false` once those\n * reports are clean for your app.\n */\n reportOnly?: boolean\n /** DSN whose ingest origin the browser may post to. */\n sentryDsn?: string\n}\n\n// Only http(s) has a meaningful `origin` — a DSN with some other scheme (or\n// no scheme at all) gives `URL.origin === \"null\"`, which would otherwise\n// become a literal \"null\" token in connect-src.\nconst HTTP_PROTOCOLS = new Set([\"http:\", \"https:\"])\n\n/** The origin a browser-side Sentry SDK for this DSN posts events to, or `undefined` for an absent/malformed DSN. */\nexport function sentryIngestOrigin(dsn: string | undefined): string | undefined {\n if (!dsn) return undefined\n try {\n const url = new URL(dsn)\n return HTTP_PROTOCOLS.has(url.protocol) ? url.origin : undefined\n } catch {\n return undefined\n }\n}\n\n// A source expression containing \";\" or a newline would end the directive and\n// start a new one — i.e. let caller-supplied config rewrite the whole policy.\n// Reject rather than strip: a silently mangled origin is a connect-src that\n// quietly fails at runtime.\nconst UNSAFE_IN_DIRECTIVE = /[;\\r\\n]/\n\nfunction assertSafe(kind: string, values: readonly string[]): void {\n for (const value of values) {\n if (UNSAFE_IN_DIRECTIVE.test(value)) {\n throw new Error(`Invalid ${kind} for CSP: ${JSON.stringify(value)} contains \";\" or a newline`)\n }\n }\n}\n\n/**\n * Build the Stage-1 QDC policy for one response.\n *\n * `script-src` carries the per-response nonce plus `'strict-dynamic'`, so a\n * script the app itself marked may load further scripts and nothing else runs.\n * `style-src` deliberately keeps `'unsafe-inline'`: HeroUI and Tailwind emit\n * inline styles, and removing it in the same change that introduces the policy\n * would break every generated app — Stage 2 replaces it with the nonce after\n * its own styling audit.\n */\nexport function buildCsp(nonce: string, options: SecurityHeaderOptions = {}): string {\n const frameAncestors = options.frameAncestors ?? [\"'none'\"]\n const frameSrc = options.frameSrc ?? [\"'self'\"]\n const connectSrc = options.connectSrc ?? []\n const reportUri = options.reportUri ?? \"/api/csp-report\"\n const sentryOrigin = sentryIngestOrigin(options.sentryDsn)\n\n assertSafe(\"nonce\", [nonce])\n assertSafe(\"frameAncestors entry\", frameAncestors)\n assertSafe(\"frameSrc entry\", frameSrc)\n assertSafe(\"connectSrc entry\", connectSrc)\n assertSafe(\"reportUri\", [reportUri])\n if (sentryOrigin) assertSafe(\"sentryDsn origin\", [sentryOrigin])\n\n const directives = [\n \"default-src 'self'\",\n `script-src 'self' 'nonce-${nonce}' 'strict-dynamic'`,\n \"style-src 'self' 'unsafe-inline'\",\n \"img-src 'self' data: blob: https:\",\n \"font-src 'self' data:\",\n \"worker-src 'self' blob:\",\n [\"connect-src\", \"'self'\", ...connectSrc, ...(sentryOrigin ? [sentryOrigin] : [])].join(\" \"),\n ...(frameSrc.length > 0 ? [[\"frame-src\", ...frameSrc].join(\" \")] : [\"frame-src 'none'\"]),\n ...(frameAncestors.length > 0 ? [[\"frame-ancestors\", ...frameAncestors].join(\" \")] : []),\n \"base-uri 'self'\",\n \"form-action 'self'\",\n \"object-src 'none'\",\n \"upgrade-insecure-requests\",\n ...(reportUri ? [`report-uri ${reportUri}`] : []),\n ]\n\n return directives.join(\"; \") + \";\"\n}\n\n/** The header name matching `options.reportOnly`. */\nexport function cspHeaderName(options: SecurityHeaderOptions = {}): string {\n return (options.reportOnly ?? true)\n ? \"Content-Security-Policy-Report-Only\"\n : \"Content-Security-Policy\"\n}\n","import { NextResponse } from \"next/server\"\nimport type { NextRequest } from \"next/server\"\n\nimport type { SecurityHeaderOptions } from \"../../security-core/csp\"\nimport { QORE_CSP_REPORT_URI } from \"../../security-core/cspReport\"\nimport { withSecurityHeaders, type ProxyHandlerFn, type SecuredProxy } from \"./index\"\n\nexport type QoreProxyAuth = \"keycloak\" | \"betterauth\" | \"none\"\n\nexport interface QoreProxyOptions {\n /** Which session the proxy pre-checks. Real validation stays server-side. */\n auth?: QoreProxyAuth\n /** Overrides for the security headers and the CSP. */\n security?: SecurityHeaderOptions\n /**\n * The app's own proxy logic. Runs after the session pre-check passes;\n * return nothing to pass through, or a Response to answer early.\n */\n handler?: ProxyHandlerFn\n}\n\n\n// Kept equal to auth-core's COOKIE_NAME by a test; imported from there it would\n// pull the session module into every proxy bundle.\nconst KEYCLOAK_SESSION_COOKIE = \"qdc_session\"\nconst BETTERAUTH_SESSION_SUFFIX = \"better-auth.session_token\"\n\nfunction keycloakGate(req: NextRequest): Response | undefined {\n if (req.cookies.has(KEYCLOAK_SESSION_COOKIE)) return undefined\n const url = req.nextUrl.clone()\n url.pathname = \"/api/auth/login\"\n url.search = \"\"\n url.searchParams.set(\"redirect\", req.nextUrl.pathname + req.nextUrl.search)\n return NextResponse.redirect(url)\n}\n\nfunction betterAuthGate(req: NextRequest): Response | undefined {\n if (req.cookies.getAll().some((c) => c.name.endsWith(BETTERAUTH_SESSION_SUFFIX))) return undefined\n const url = req.nextUrl.clone()\n url.pathname = \"/login\"\n return NextResponse.redirect(url)\n}\n\nconst GATES: Record<QoreProxyAuth, ((req: NextRequest) => Response | undefined) | null> = {\n keycloak: keycloakGate,\n betterauth: betterAuthGate,\n none: null,\n}\n\n/**\n * The body of a Next app's `src/proxy.ts`: security headers and a CSP nonce on\n * every response, a cheap session-cookie pre-check that redirects to login,\n * then the app's own handler. Which paths it covers stays the app's `config`\n * literal, since Next reads that statically.\n */\nexport function qoreProxy(options: QoreProxyOptions = {}): SecuredProxy {\n const gate = GATES[options.auth ?? \"none\"]\n const handler = options.handler\n return withSecurityHeaders(\n async (req, event) => gate?.(req) ?? (handler ? handler(req, event) : undefined),\n { reportUri: QORE_CSP_REPORT_URI, ...options.security },\n )\n}\n","// The API level contract, server side. The app's `src/config/mobile.ts` holds\n// `MOBILE_API_LEVEL` (what this server speaks) and `MOBILE_MIN_API_LEVEL` (the\n// oldest phone build it still serves). The portal refuses a promote whose\n// minimum is above what the environment's installed builds speak, so a server\n// never runs ahead of its clients; these helpers are the runtime half.\n// The header name is kept equal to `expo/core/apiLevel.ts` by a test.\n\nexport const API_LEVEL_HEADER = \"x-qore-api-level\"\n\nexport interface MobileApiLevels {\n /** The API level this server speaks. */\n apiLevel: number\n /** The oldest phone build's level this server still serves. */\n minApiLevel: number\n}\n\nfunction assertLevels({ apiLevel, minApiLevel }: MobileApiLevels): void {\n for (const [name, v] of [[\"apiLevel\", apiLevel], [\"minApiLevel\", minApiLevel]] as const) {\n if (!Number.isInteger(v) || v < 0) throw new Error(`${name} must be a non-negative integer, got ${v}`)\n }\n if (minApiLevel > apiLevel) throw new Error(`minApiLevel (${minApiLevel}) is above apiLevel (${apiLevel})`)\n}\n\n/**\n * 426 for a phone build below `minApiLevel`, else `null`. A request without\n * the header passes: the web pages call the same routes, and a build from\n * before the contract cannot be told apart from them. A header that is not an\n * integer counts as level 0.\n */\nexport function requireMobileApiLevel(req: Request, minApiLevel: number): Response | null {\n const raw = req.headers.get(API_LEVEL_HEADER)\n if (raw === null) return null\n const level = /^\\d{1,6}$/.test(raw.trim()) ? Number(raw.trim()) : 0\n if (level >= minApiLevel) return null\n return Response.json(\n { error: \"upgrade_required\", minApiLevel },\n { status: 426, headers: { \"cache-control\": \"no-store\" } },\n )\n}\n\n/**\n * The app's `src/app/api/qore/app-version/route.ts`: a public GET that tells a\n * phone whether its build is still served. Throws at import when the levels\n * contradict each other, so a bad edit fails the build rather than a device.\n */\nexport function createAppVersionRoute(levels: MobileApiLevels): { GET: () => Response } {\n assertLevels(levels)\n const body = { apiLevel: levels.apiLevel, minApiLevel: levels.minApiLevel }\n return {\n GET: () => Response.json(body, { headers: { \"cache-control\": \"no-store\" } }),\n }\n}\n"],"mappings":";;;;;;;;;;;;;;AAAA,SAAS,gBAAAA,qBAAoB;;;ACgD7B,IAAM,iBAAiB,oBAAI,IAAI,CAAC,SAAS,QAAQ,CAAC;AAG3C,SAAS,mBAAmB,KAA6C;AAC9E,MAAI,CAAC,IAAK,QAAO;AACjB,MAAI;AACF,UAAM,MAAM,IAAI,IAAI,GAAG;AACvB,WAAO,eAAe,IAAI,IAAI,QAAQ,IAAI,IAAI,SAAS;AAAA,EACzD,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAMA,IAAM,sBAAsB;AAE5B,SAAS,WAAW,MAAc,QAAiC;AACjE,aAAW,SAAS,QAAQ;AAC1B,QAAI,oBAAoB,KAAK,KAAK,GAAG;AACnC,YAAM,IAAI,MAAM,WAAW,IAAI,aAAa,KAAK,UAAU,KAAK,CAAC,4BAA4B;AAAA,IAC/F;AAAA,EACF;AACF;AAYO,SAAS,SAAS,OAAe,UAAiC,CAAC,GAAW;AACnF,QAAM,iBAAiB,QAAQ,kBAAkB,CAAC,QAAQ;AAC1D,QAAM,WAAW,QAAQ,YAAY,CAAC,QAAQ;AAC9C,QAAM,aAAa,QAAQ,cAAc,CAAC;AAC1C,QAAM,YAAY,QAAQ,aAAa;AACvC,QAAM,eAAe,mBAAmB,QAAQ,SAAS;AAEzD,aAAW,SAAS,CAAC,KAAK,CAAC;AAC3B,aAAW,wBAAwB,cAAc;AACjD,aAAW,kBAAkB,QAAQ;AACrC,aAAW,oBAAoB,UAAU;AACzC,aAAW,aAAa,CAAC,SAAS,CAAC;AACnC,MAAI,aAAc,YA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M,QAAQ,SAAS,KAAK;AAE5C,QAAI;AACJ,QAAI,CAAC,SAAS;AACZ,iBAAWC,cAAa,KAAK,EAAE,SAAS,EAAE,SAAS,eAAe,EAAE,CAAC;AAAA,IACvE,WAAW,cAAc,OAAO,GAAG;AACjC,iBAAWA,cAAa,KAAK,EAAE,SAAS,EAAE,SAAS,eAAe,EAAE,CAAC;AACrE,gBAAU,SAAS,QAAQ;AAAA,IAC7B,OAAO;AAIL,iBAAW;AAAA,IACb;AAEA,yBAAqB,UAAU,SAAS,GAAG;AAC3C,WAAO;AAAA,EACT;AACF;","names":["NextResponse","NextResponse"]}
@@ -3,10 +3,10 @@ import {
3
3
  } from "../../chunk-DYOSRJH3.js";
4
4
  import {
5
5
  initSentry
6
- } from "../../chunk-YFZB5EW6.js";
6
+ } from "../../chunk-P5GBQVO7.js";
7
7
  import "../../chunk-MET4SIMB.js";
8
8
  import "../../chunk-7ASQHY7O.js";
9
- import "../../chunk-IFESUTF2.js";
9
+ import "../../chunk-VQKYPW5V.js";
10
10
 
11
11
  // src/next/sentry/client.ts
12
12
  import * as Sentry from "@sentry/nextjs";
@@ -24,7 +24,7 @@ function initBrowser(doc, sentry) {
24
24
  cfg,
25
25
  () => cfg?.local ? {} : {
26
26
  integrations: [sentry.replayIntegration(REPLAY_PRIVACY)],
27
- replaysSessionSampleRate: 0,
27
+ replaysSessionSampleRate: cfg?.environment === "production" ? 0.1 : 1,
28
28
  replaysOnErrorSampleRate: 1
29
29
  }
30
30
  );
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/next/sentry/client.ts"],"sourcesContent":["import * as Sentry from \"@sentry/nextjs\"\nimport { initSentry, type SentryLike } from \"../../sentry-core/init\"\nimport { readRuntimeConfig } from \"../../sentry-core/runtime-config\"\n\n// maskAllInputs skips type=\"hidden\", whose values (CSRF tokens, ids) would otherwise be\n// recorded as-is; blocking them drops the element and its input events.\nconst REPLAY_PRIVACY = {\n maskAllText: true, maskAllInputs: true, blockAllMedia: true, block: ['input[type=\"hidden\"]'],\n}\n\ntype BrowserSentry = SentryLike & { replayIntegration(options: object): unknown }\n\nexport function initBrowser(doc: Document, sentry: BrowserSentry): boolean {\n const cfg = readRuntimeConfig(doc)\n // Locally a replay would only print binary segments; errors and logs are what matter there.\n return initSentry(sentry, \"browser\", cfg, () =>\n cfg?.local\n ? {}\n : {\n integrations: [sentry.replayIntegration(REPLAY_PRIVACY)],\n replaysSessionSampleRate: 0,\n replaysOnErrorSampleRate: 1,\n },\n )\n}\n\nif (typeof document !== \"undefined\") initBrowser(document, Sentry)\n\nexport const onRouterTransitionStart = Sentry.captureRouterTransitionStart\n"],"mappings":";;;;;;;;;;;AAAA,YAAY,YAAY;AAMxB,IAAM,iBAAiB;AAAA,EACrB,aAAa;AAAA,EAAM,eAAe;AAAA,EAAM,eAAe;AAAA,EAAM,OAAO,CAAC,sBAAsB;AAC7F;AAIO,SAAS,YAAY,KAAe,QAAgC;AACzE,QAAM,MAAM,kBAAkB,GAAG;AAEjC,SAAO;AAAA,IAAW;AAAA,IAAQ;AAAA,IAAW;AAAA,IAAK,MACxC,KAAK,QACD,CAAC,IACD;AAAA,MACE,cAAc,CAAC,OAAO,kBAAkB,cAAc,CAAC;AAAA,MACvD,0BAA0B;AAAA,MAC1B,0BAA0B;AAAA,IAC5B;AAAA,EACN;AACF;AAEA,IAAI,OAAO,aAAa,YAAa,aAAY,UAAU,MAAM;AAE1D,IAAM,0BAAiC;","names":[]}
1
+ {"version":3,"sources":["../../../src/next/sentry/client.ts"],"sourcesContent":["import * as Sentry from \"@sentry/nextjs\"\nimport { initSentry, type SentryLike } from \"../../sentry-core/init\"\nimport { readRuntimeConfig } from \"../../sentry-core/runtime-config\"\n\n// maskAllInputs skips type=\"hidden\", whose values (CSRF tokens, ids) would otherwise be\n// recorded as-is; blocking them drops the element and its input events.\nconst REPLAY_PRIVACY = {\n maskAllText: true, maskAllInputs: true, blockAllMedia: true, block: ['input[type=\"hidden\"]'],\n}\n\ntype BrowserSentry = SentryLike & { replayIntegration(options: object): unknown }\n\nexport function initBrowser(doc: Document, sentry: BrowserSentry): boolean {\n const cfg = readRuntimeConfig(doc)\n // Locally a replay would only print binary segments; errors and logs are what matter there.\n // Elsewhere every session is recorded (masked) outside production, a tenth in production:\n // a replay is most useful exactly when nobody thought to reproduce the bug.\n return initSentry(sentry, \"browser\", cfg, () =>\n cfg?.local\n ? {}\n : {\n integrations: [sentry.replayIntegration(REPLAY_PRIVACY)],\n replaysSessionSampleRate: cfg?.environment === \"production\" ? 0.1 : 1,\n replaysOnErrorSampleRate: 1,\n },\n )\n}\n\nif (typeof document !== \"undefined\") initBrowser(document, Sentry)\n\nexport const onRouterTransitionStart = Sentry.captureRouterTransitionStart\n"],"mappings":";;;;;;;;;;;AAAA,YAAY,YAAY;AAMxB,IAAM,iBAAiB;AAAA,EACrB,aAAa;AAAA,EAAM,eAAe;AAAA,EAAM,eAAe;AAAA,EAAM,OAAO,CAAC,sBAAsB;AAC7F;AAIO,SAAS,YAAY,KAAe,QAAgC;AACzE,QAAM,MAAM,kBAAkB,GAAG;AAIjC,SAAO;AAAA,IAAW;AAAA,IAAQ;AAAA,IAAW;AAAA,IAAK,MACxC,KAAK,QACD,CAAC,IACD;AAAA,MACE,cAAc,CAAC,OAAO,kBAAkB,cAAc,CAAC;AAAA,MACvD,0BAA0B,KAAK,gBAAgB,eAAe,MAAM;AAAA,MACpE,0BAA0B;AAAA,IAC5B;AAAA,EACN;AACF;AAEA,IAAI,OAAO,aAAa,YAAa,aAAY,UAAU,MAAM;AAE1D,IAAM,0BAAiC;","names":[]}
@@ -7,7 +7,7 @@ import {
7
7
  } from "../../chunk-7ASQHY7O.js";
8
8
  import {
9
9
  registerSecretValues
10
- } from "../../chunk-IFESUTF2.js";
10
+ } from "../../chunk-VQKYPW5V.js";
11
11
 
12
12
  // src/next/sentry/index.tsx
13
13
  import { connection } from "next/server";
@@ -1,11 +1,11 @@
1
1
  import {
2
2
  onRequestError,
3
3
  register
4
- } from "../../chunk-POZI4OKJ.js";
5
- import "../../chunk-YFZB5EW6.js";
4
+ } from "../../chunk-WOFBDOMY.js";
5
+ import "../../chunk-P5GBQVO7.js";
6
6
  import "../../chunk-MET4SIMB.js";
7
7
  import "../../chunk-7ASQHY7O.js";
8
- import "../../chunk-IFESUTF2.js";
8
+ import "../../chunk-VQKYPW5V.js";
9
9
  export {
10
10
  onRequestError,
11
11
  register
@@ -0,0 +1,28 @@
1
+ import { NodePgDatabase } from 'drizzle-orm/node-postgres';
2
+
3
+ interface MigrationDb {
4
+ readonly db: NodePgDatabase;
5
+ readonly close: () => Promise<void>;
6
+ }
7
+ declare function createMigrationDb(databaseUrl: string): MigrationDb;
8
+ declare function parseRoleFromUrl(databaseUrl: string): string;
9
+ declare function grantRuntimeDefaultPrivileges(db: NodePgDatabase, schema: string, runtimeRole: string): Promise<void>;
10
+
11
+ interface MigrateAppOptions {
12
+ /** The Postgres schema the app's tables live in (`appSchema.schemaName`, or `"public"`). */
13
+ schema: string;
14
+ /** Defaults to `<cwd>/src/db/migrations`, where `pnpm db:generate` writes. */
15
+ migrationsFolder?: string;
16
+ /** The runtime role's DSN. Defaults to `DATABASE_URL`. */
17
+ databaseUrl?: string;
18
+ /** The migrator role's DSN. Defaults to `MIGRATION_DATABASE_URL`. */
19
+ migrationDatabaseUrl?: string;
20
+ }
21
+ /**
22
+ * Applies the app's drizzle-kit migrations as the migrator role, then grants
23
+ * the runtime role access to what they created. Safe on every boot: drizzle
24
+ * skips applied migrations and the grant is a no-op when both roles are one.
25
+ */
26
+ declare function migrateApp(options: MigrateAppOptions): Promise<void>;
27
+
28
+ export { type MigrateAppOptions, type MigrationDb, createMigrationDb, grantRuntimeDefaultPrivileges, migrateApp, parseRoleFromUrl };
@@ -0,0 +1,16 @@
1
+ import {
2
+ migrateApp
3
+ } from "../../../chunk-S7TJQVXV.js";
4
+ import {
5
+ createMigrationDb,
6
+ grantRuntimeDefaultPrivileges,
7
+ parseRoleFromUrl
8
+ } from "../../../chunk-BJN7YE63.js";
9
+ import "../../../chunk-4MBB2UQW.js";
10
+ export {
11
+ createMigrationDb,
12
+ grantRuntimeDefaultPrivileges,
13
+ migrateApp,
14
+ parseRoleFromUrl
15
+ };
16
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  registerSecretValues
3
- } from "../../chunk-IFESUTF2.js";
3
+ } from "../../chunk-VQKYPW5V.js";
4
4
  export {
5
5
  registerSecretValues
6
6
  };
@@ -1,11 +1,11 @@
1
1
  import {
2
2
  initSentry
3
- } from "../../chunk-YFZB5EW6.js";
3
+ } from "../../chunk-P5GBQVO7.js";
4
4
  import "../../chunk-MET4SIMB.js";
5
5
  import {
6
6
  readSentryConfig
7
7
  } from "../../chunk-7ASQHY7O.js";
8
- import "../../chunk-IFESUTF2.js";
8
+ import "../../chunk-VQKYPW5V.js";
9
9
 
10
10
  // src/node/sentry/register.ts
11
11
  import * as Sentry from "@sentry/node";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@quatronic/sdk",
3
- "version": "0.10.1",
3
+ "version": "0.11.0-test.014be98",
4
4
  "type": "module",
5
5
  "private": false,
6
6
  "publishConfig": {
@@ -124,6 +124,10 @@
124
124
  "types": "./dist/node/db/index.d.ts",
125
125
  "import": "./dist/node/db/index.js"
126
126
  },
127
+ "./node/db/migrate": {
128
+ "types": "./dist/node/db/migrate/index.d.ts",
129
+ "import": "./dist/node/db/migrate/index.js"
130
+ },
127
131
  "./next/db": {
128
132
  "types": "./dist/next/db/index.d.ts",
129
133
  "import": "./dist/next/db/index.js"
@@ -147,6 +151,48 @@
147
151
  "./next/platform": {
148
152
  "types": "./dist/next/platform/index.d.ts",
149
153
  "import": "./dist/next/platform/index.js"
154
+ },
155
+ "./expo/auth": {
156
+ "types": "./dist/expo/auth/index.d.ts",
157
+ "react-native": "./dist/expo/auth/index.js",
158
+ "import": "./dist/expo/auth/index.js",
159
+ "default": "./dist/expo/auth/index.js"
160
+ },
161
+ "./expo/query": {
162
+ "types": "./dist/expo/query/index.d.ts",
163
+ "react-native": "./dist/expo/query/index.js",
164
+ "import": "./dist/expo/query/index.js",
165
+ "default": "./dist/expo/query/index.js"
166
+ },
167
+ "./expo/updates": {
168
+ "types": "./dist/expo/updates/index.d.ts",
169
+ "react-native": "./dist/expo/updates/index.js",
170
+ "import": "./dist/expo/updates/index.js",
171
+ "default": "./dist/expo/updates/index.js"
172
+ },
173
+ "./expo/sentry": {
174
+ "types": "./dist/expo/sentry/index.d.ts",
175
+ "react-native": "./dist/expo/sentry/index.js",
176
+ "import": "./dist/expo/sentry/index.js",
177
+ "default": "./dist/expo/sentry/index.js"
178
+ },
179
+ "./expo/log": {
180
+ "types": "./dist/expo/log/index.d.ts",
181
+ "react-native": "./dist/expo/log/index.js",
182
+ "import": "./dist/expo/log/index.js",
183
+ "default": "./dist/expo/log/index.js"
184
+ },
185
+ "./expo/config": {
186
+ "types": "./dist/expo/config/index.d.ts",
187
+ "react-native": "./dist/expo/config/index.js",
188
+ "import": "./dist/expo/config/index.js",
189
+ "default": "./dist/expo/config/index.js"
190
+ },
191
+ "./expo/testing": {
192
+ "types": "./dist/expo/testing/index.d.ts",
193
+ "react-native": "./dist/expo/testing/index.js",
194
+ "import": "./dist/expo/testing/index.js",
195
+ "default": "./dist/expo/testing/index.js"
150
196
  }
151
197
  },
152
198
  "scripts": {
@@ -169,15 +215,25 @@
169
215
  },
170
216
  "peerDependencies": {
171
217
  "@better-auth/core": ">=1.6",
218
+ "@react-native-community/netinfo": ">=12",
172
219
  "@sentry/nextjs": "^10",
173
220
  "@sentry/node": "^10",
221
+ "@sentry/react-native": ">=8",
222
+ "@tanstack/react-query": "^5",
174
223
  "better-auth": ">=1.6",
175
224
  "drizzle-orm": ">=0.36",
176
225
  "eslint": ">=9",
226
+ "expo-constants": ">=58",
227
+ "expo-crypto": ">=58",
228
+ "expo-linking": ">=58",
229
+ "expo-secure-store": ">=58",
230
+ "expo-updates": ">=58",
231
+ "expo-web-browser": ">=58",
177
232
  "next": ">=15",
178
233
  "pg": ">=8.13",
179
234
  "react": ">=18",
180
- "react-dom": ">=18"
235
+ "react-dom": ">=18",
236
+ "react-native": ">=0.88"
181
237
  },
182
238
  "peerDependenciesMeta": {
183
239
  "eslint": {
@@ -209,6 +265,36 @@
209
265
  },
210
266
  "@sentry/node": {
211
267
  "optional": true
268
+ },
269
+ "@react-native-community/netinfo": {
270
+ "optional": true
271
+ },
272
+ "@sentry/react-native": {
273
+ "optional": true
274
+ },
275
+ "@tanstack/react-query": {
276
+ "optional": true
277
+ },
278
+ "expo-constants": {
279
+ "optional": true
280
+ },
281
+ "expo-crypto": {
282
+ "optional": true
283
+ },
284
+ "expo-linking": {
285
+ "optional": true
286
+ },
287
+ "expo-secure-store": {
288
+ "optional": true
289
+ },
290
+ "expo-updates": {
291
+ "optional": true
292
+ },
293
+ "expo-web-browser": {
294
+ "optional": true
295
+ },
296
+ "react-native": {
297
+ "optional": true
212
298
  }
213
299
  },
214
300
  "devDependencies": {
@@ -217,6 +303,7 @@
217
303
  "@opentelemetry/sdk-trace-base": "^2.7.0",
218
304
  "@sentry/nextjs": "10.75.2",
219
305
  "@sentry/node": "10.75.2",
306
+ "@tanstack/react-query": "^5.105.3",
220
307
  "@testcontainers/postgresql": "^12.0.0",
221
308
  "@testing-library/react": "^16.1.0",
222
309
  "@types/jscodeshift": "17.3.0",
@@ -10,13 +10,16 @@
10
10
  {"name": "qore-author-skill", "kind": "convenience", "legacyNames": ["quatronic-author-skill"]},
11
11
  {"name": "qore-debug-issue", "kind": "convenience"},
12
12
  {"name": "qore-enable-auth-method", "kind": "convenience", "requires": ["auth=betterauth"], "legacyNames": ["quatronic-enable-auth-method"]},
13
+ {"name": "qore-mobile-add-screen", "kind": "convenience", "requires": ["mobile"]},
14
+ {"name": "qore-mobile-call-server", "kind": "convenience", "requires": ["mobile"]},
15
+ {"name": "qore-mobile-run-on-device", "kind": "convenience", "requires": ["mobile"]},
13
16
  {"name": "qore-observability", "kind": "contract", "legacyNames": ["quatronic-observe"]},
14
17
  {"name": "qore-recommended-tools", "kind": "convenience", "requires": ["runtime=next"], "legacyNames": ["quatronic-recommended-tools"]},
15
18
  {"name": "qore-secure-io", "kind": "convenience", "requires": ["runtime=next"], "legacyNames": ["quatronic-secure-io"]},
16
19
  {"name": "qore-ship-checklist", "kind": "convenience", "requires": ["runtime=next"], "legacyNames": ["quatronic-ship-checklist"]},
17
20
  {"name": "qore-translate-strings", "kind": "convenience", "requires": ["runtime=next"], "legacyNames": ["quatronic-translate-strings"]},
18
21
  {"name": "qore-use-addons", "kind": "convenience", "requires": ["runtime=next"], "legacyNames": ["quatronic-use-addons"]},
19
- {"name": "qore-use-database", "kind": "contract", "requires": ["runtime=node", "db"], "legacyNames": ["quatronic-use-database"]},
22
+ {"name": "qore-use-database", "kind": "contract", "requires": ["runtime=node"], "legacyNames": ["quatronic-use-database"]},
20
23
  {"name": "qore-use-design-system", "kind": "convenience", "requires": ["runtime=next"], "legacyNames": ["quatronic-use-design-system"]},
21
24
  {"name": "qore-use-mail-domain", "kind": "convenience", "legacyNames": ["quatronic-use-mail-domain"]},
22
25
  {"name": "qore-use-permissions", "kind": "contract", "requires": ["auth=keycloak"], "legacyNames": ["quatronic-use-permissions"]},
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: qore-add-api-route
3
- description: Add a business HTTP route under src/app/api/ for external callers{{#if auth}}, protected with the SDK{{/if}}. Use for API endpoints — internal mutations are Server Actions, not routes.
3
+ description: Add a business HTTP route under src/app/api/ for external callers{{#if auth}}, protected with the SDK{{/if}}. Use for API endpoints — internal mutations are Server Actions, not routes.{{#if mobile}} Also the server half of anything the phone app calls (see qore-mobile-call-server).{{/if}}
4
4
  allowed-tools: Bash(pnpm:*), Edit, Read
5
5
  ---
6
6