create-signet-app 0.8.3 → 0.9.1
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/base/api/api/app.ts +15 -1
- package/base/api/api/env.ts +4 -0
- package/base/api/api/services.ts +55 -1
- package/package.json +3 -2
- package/parts/auth/api/api/routes/auth.ts +31 -8
- package/parts/mobile/api/api/routes/mobile.ts +71 -0
- package/parts/mobile/api/test/mobile.test.ts +104 -0
- package/parts/mobile/part.ts +11 -0
- package/parts/pwa/web/public/icon-192.png +0 -0
- package/parts/pwa/web/public/icon-512.png +0 -0
- package/parts/pwa/web/public/icon-maskable-512.png +0 -0
- package/parts/pwa/web/public/manifest.webmanifest +11 -1
- package/parts/pwa/web/public/sw.js +8 -1
- package/src/compose.ts +15 -4
- package/src/index.ts +53 -13
- package/src/mobile.ts +61 -0
- package/src/picker.ts +21 -8
- package/template-mobile/README.md +142 -0
- package/template-mobile/_github/workflows/ci.yml +38 -0
- package/template-mobile/_gitignore +1 -0
- package/template-mobile/mobile/_gitignore +16 -0
- package/template-mobile/mobile/app.config.ts +77 -0
- package/template-mobile/mobile/assets/adaptive-icon.png +0 -0
- package/template-mobile/mobile/assets/icon.png +0 -0
- package/template-mobile/mobile/assets/notification-icon.png +0 -0
- package/template-mobile/mobile/assets/splash-icon.png +0 -0
- package/template-mobile/mobile/babel.config.js +4 -0
- package/template-mobile/mobile/biome.json +8 -0
- package/template-mobile/mobile/eas.json +27 -0
- package/template-mobile/mobile/expo-env.d.ts +1 -0
- package/template-mobile/mobile/jest.config.js +9 -0
- package/template-mobile/mobile/jest.setup.js +32 -0
- package/template-mobile/mobile/src/__tests__/auth-gate.test.tsx +40 -0
- package/template-mobile/mobile/src/__tests__/sign-in.test.tsx +41 -0
- package/template-mobile/mobile/src/app/(app)/_layout.tsx +48 -0
- package/template-mobile/mobile/src/app/(app)/devices/[id].tsx +62 -0
- package/template-mobile/mobile/src/app/(app)/devices/_layout.tsx +19 -0
- package/template-mobile/mobile/src/app/(app)/devices/index.tsx +40 -0
- package/template-mobile/mobile/src/app/(app)/index.tsx +69 -0
- package/template-mobile/mobile/src/app/(app)/settings.tsx +116 -0
- package/template-mobile/mobile/src/app/(auth)/_layout.tsx +19 -0
- package/template-mobile/mobile/src/app/(auth)/sign-in.tsx +49 -0
- package/template-mobile/mobile/src/app/(auth)/verify.tsx +62 -0
- package/template-mobile/mobile/src/app/_layout.tsx +95 -0
- package/template-mobile/mobile/src/components/ui.tsx +230 -0
- package/template-mobile/mobile/src/lib/analytics.ts +20 -0
- package/template-mobile/mobile/src/lib/api.ts +49 -0
- package/template-mobile/mobile/src/lib/auth.ts +43 -0
- package/template-mobile/mobile/src/lib/config.ts +14 -0
- package/template-mobile/mobile/src/lib/devices.ts +18 -0
- package/template-mobile/mobile/src/lib/outbox.ts +84 -0
- package/template-mobile/mobile/src/lib/polyfills.ts +19 -0
- package/template-mobile/mobile/src/lib/push.ts +97 -0
- package/template-mobile/mobile/src/lib/session.ts +39 -0
- package/template-mobile/mobile/src/lib/storage.ts +17 -0
- package/template-mobile/mobile/src/lib/theme.tsx +64 -0
- package/template-mobile/mobile/tsconfig.json +11 -0
package/base/api/api/app.ts
CHANGED
|
@@ -41,6 +41,7 @@ import { authRoutes, requireUser } from "./routes/auth.ts" // @auth
|
|
|
41
41
|
// payments:begin
|
|
42
42
|
import { billingRoutes, billingWebhooks } from "./routes/billing.ts"
|
|
43
43
|
// payments:end
|
|
44
|
+
import { mobileRoutes } from "./routes/mobile.ts" // @mobile
|
|
44
45
|
// notifications:begin
|
|
45
46
|
import { notificationRoutes } from "./routes/notifications.ts"
|
|
46
47
|
// notifications:end
|
|
@@ -69,6 +70,7 @@ const SIGNED_IN = [
|
|
|
69
70
|
"/api/ai", // AI calls, within the spend caps // @ai
|
|
70
71
|
"/api/paywall", // the paywall for a placement // @paywalls
|
|
71
72
|
"/api/workflows", // workflow runs and approvals // @workflows
|
|
73
|
+
"/api/mobile/push", // the phone's push token, a test push // @mobile
|
|
72
74
|
]
|
|
73
75
|
// auth:end
|
|
74
76
|
|
|
@@ -103,7 +105,18 @@ export function createApp(deps: Deps) {
|
|
|
103
105
|
}
|
|
104
106
|
// Blocks cross-site form posts riding the session cookie. The web app is
|
|
105
107
|
// served from this same origin, so nothing else needs trusting.
|
|
106
|
-
base.use("/api/*", csrfMiddleware())
|
|
108
|
+
base.use("/api/*", csrfMiddleware()) // @!mobile
|
|
109
|
+
// mobile:begin
|
|
110
|
+
// Not the mobile token routes: they read the refresh token from the body
|
|
111
|
+
// (a form post, as OAuth has it), never the cookie, so a forged post has
|
|
112
|
+
// nothing to ride.
|
|
113
|
+
const csrf = csrfMiddleware()
|
|
114
|
+
base.use("/api/*", (c, next) =>
|
|
115
|
+
c.req.path === "/api/mobile/token" || c.req.path === "/api/mobile/revoke"
|
|
116
|
+
? next()
|
|
117
|
+
: csrf(c, next),
|
|
118
|
+
)
|
|
119
|
+
// mobile:end
|
|
107
120
|
base.use("/api/*", rateLimit<AppEnv>({ store: memoryStore(), trust: TRUST, max: 300 }))
|
|
108
121
|
// auth:begin
|
|
109
122
|
for (const path of SIGNED_IN) base.use(`${path}/*`, requireUser(s))
|
|
@@ -137,6 +150,7 @@ export function createApp(deps: Deps) {
|
|
|
137
150
|
.route("/api/sessions", sessionRoutes(s.sessions))
|
|
138
151
|
.route("/api/account", accountRoutes(s))
|
|
139
152
|
// auth:end
|
|
153
|
+
.route("/api/mobile", mobileRoutes(s)) // @mobile
|
|
140
154
|
// notifications:begin
|
|
141
155
|
.route("/api/notifications", notificationRoutes(s))
|
|
142
156
|
// notifications:end
|
package/base/api/api/env.ts
CHANGED
|
@@ -18,6 +18,10 @@ export const envSchema = z.object({
|
|
|
18
18
|
/** Comma-separated phone numbers (E.164) that get the admin role on sign-in. */
|
|
19
19
|
ADMIN_PHONES: z.string().default(""),
|
|
20
20
|
// auth:end
|
|
21
|
+
// mobile:begin
|
|
22
|
+
/** Expo push access token, needed once push security is on in the Expo project. */
|
|
23
|
+
EXPO_ACCESS_TOKEN: z.string().optional(),
|
|
24
|
+
// mobile:end
|
|
21
25
|
// payments:begin
|
|
22
26
|
/**
|
|
23
27
|
* "fake": Upgrade switches the plan at once and no money moves. Refused in
|
package/base/api/api/services.ts
CHANGED
|
@@ -25,10 +25,12 @@ import { kvRateLimitStore } from "@dapplelight/signet-server/adapters"
|
|
|
25
25
|
// account:begin
|
|
26
26
|
import { kvApiKeyStore } from "@dapplelight/signet-server/auth/api-keys"
|
|
27
27
|
// account:end
|
|
28
|
+
import type { ClientLoginOptions } from "@dapplelight/signet-server/auth/client-login" // @mobile
|
|
28
29
|
// auth:begin
|
|
29
30
|
import { devSmsSender, type SmsSender } from "@dapplelight/signet-server/auth/otp"
|
|
30
31
|
import { kvSessionStore } from "@dapplelight/signet-server/auth/sessions"
|
|
31
32
|
// auth:end
|
|
33
|
+
import { expoPushSender } from "@dapplelight/signet-server/notify/channels" // @mobile
|
|
32
34
|
// notifications:begin
|
|
33
35
|
import {
|
|
34
36
|
createNotifier,
|
|
@@ -160,6 +162,8 @@ export function createServices({ db, kv }: Deps) { // @!auth
|
|
|
160
162
|
cookieName: "session",
|
|
161
163
|
secret: env.SESSION_SECRET,
|
|
162
164
|
store: kvSessionStore(kv),
|
|
165
|
+
// The mobile app sends `Authorization: Bearer`; the web app's cookie still works. // @mobile
|
|
166
|
+
bearer: true, // @mobile
|
|
163
167
|
}
|
|
164
168
|
const rateLimit = kvRateLimitStore(kv)
|
|
165
169
|
const otp = {
|
|
@@ -171,9 +175,54 @@ export function createServices({ db, kv }: Deps) { // @!auth
|
|
|
171
175
|
rateLimit,
|
|
172
176
|
}
|
|
173
177
|
// auth:end
|
|
178
|
+
// mobile:begin
|
|
179
|
+
// The mobile app signs in with a phone code too, then holds a token pair
|
|
180
|
+
// instead of the cookie (routes/auth.ts, routes/mobile.ts). No device or
|
|
181
|
+
// browser flow is mounted, so the verification page is never shown.
|
|
182
|
+
const clientLogin: ClientLoginOptions = {
|
|
183
|
+
sessions,
|
|
184
|
+
kv,
|
|
185
|
+
rateLimit,
|
|
186
|
+
clients: { mobile: {} },
|
|
187
|
+
verificationUri: "",
|
|
188
|
+
}
|
|
189
|
+
// Each user's Expo push tokens, newest last, in the kv table.
|
|
190
|
+
// ponytail: read-modify-write per user; a table with a unique token column at scale.
|
|
191
|
+
// A token belongs to one user at a time (push-owner:<token>): when another
|
|
192
|
+
// account turns push on from the same phone, the previous owner loses it,
|
|
193
|
+
// even if their sign-out never reached the server.
|
|
194
|
+
const pushKey = (userId: string) => `push-tokens:${userId}`
|
|
195
|
+
const ownerKey = (token: string) => `push-owner:${token}`
|
|
196
|
+
const dropFrom = async (userId: string, token: string) => {
|
|
197
|
+
const kept = (await pushTokens.list(userId)).filter((t) => t !== token)
|
|
198
|
+
await kv.set(pushKey(userId), JSON.stringify(kept))
|
|
199
|
+
}
|
|
200
|
+
const pushTokens = {
|
|
201
|
+
async list(userId: string): Promise<string[]> {
|
|
202
|
+
return JSON.parse((await kv.get(pushKey(userId))) ?? "[]") as string[]
|
|
203
|
+
},
|
|
204
|
+
async add(userId: string, token: string) {
|
|
205
|
+
const previous = await kv.get(ownerKey(token))
|
|
206
|
+
if (previous && previous !== userId) await dropFrom(previous, token)
|
|
207
|
+
await kv.set(ownerKey(token), userId)
|
|
208
|
+
const kept = (await pushTokens.list(userId)).filter((t) => t !== token)
|
|
209
|
+
await kv.set(pushKey(userId), JSON.stringify([...kept, token].slice(-10)))
|
|
210
|
+
},
|
|
211
|
+
async remove(token: string, userId: string) {
|
|
212
|
+
await dropFrom(userId, token)
|
|
213
|
+
if ((await kv.get(ownerKey(token))) === userId) await kv.delete(ownerKey(token))
|
|
214
|
+
},
|
|
215
|
+
}
|
|
216
|
+
const push = expoPushSender({
|
|
217
|
+
tokens: pushTokens.list,
|
|
218
|
+
removeToken: pushTokens.remove,
|
|
219
|
+
...(env.EXPO_ACCESS_TOKEN ? { accessToken: env.EXPO_ACCESS_TOKEN } : {}),
|
|
220
|
+
})
|
|
221
|
+
// mobile:end
|
|
174
222
|
// notifications:begin
|
|
175
223
|
const notifier = createNotifier({
|
|
176
|
-
channels: {},
|
|
224
|
+
channels: { push }, // a template with a push variant reaches the phone // @mobile
|
|
225
|
+
channels: {}, // @!mobile
|
|
177
226
|
templates,
|
|
178
227
|
store: kvNotifyStore(kv),
|
|
179
228
|
recipients: async (id) => {
|
|
@@ -242,6 +291,11 @@ export function createServices({ db, kv }: Deps) { // @!auth
|
|
|
242
291
|
rateLimit,
|
|
243
292
|
otp,
|
|
244
293
|
// auth:end
|
|
294
|
+
// mobile:begin
|
|
295
|
+
clientLogin,
|
|
296
|
+
pushTokens,
|
|
297
|
+
push,
|
|
298
|
+
// mobile:end
|
|
245
299
|
apiKeys: kvApiKeyStore(kv), // @account
|
|
246
300
|
notifier, // @notifications
|
|
247
301
|
// payments:begin
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "create-signet-app",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.9.1",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"description": "Scaffold a Vite + React + Tailwind app wired to Signet.",
|
|
6
6
|
"keywords": [
|
|
@@ -33,12 +33,13 @@
|
|
|
33
33
|
"template-cli",
|
|
34
34
|
"template-extension",
|
|
35
35
|
"template-desktop",
|
|
36
|
+
"template-mobile",
|
|
36
37
|
"base",
|
|
37
38
|
"parts"
|
|
38
39
|
],
|
|
39
40
|
"scripts": {
|
|
40
41
|
"typecheck": "tsc --noEmit && tsc --noEmit -p tsconfig.test.json",
|
|
41
|
-
"test": "bun run test/scaffold.ts && bun run test/scaffold-api.ts && bun run test/scaffold-full.ts && bun run test/scaffold-cli.ts && bun run test/scaffold-extension.ts && bun run test/scaffold-desktop.ts && bun run test/describe.ts && bun run test/picker.ts",
|
|
42
|
+
"test": "bun run test/scaffold.ts && bun run test/scaffold-api.ts && bun run test/scaffold-full.ts && bun run test/scaffold-cli.ts && bun run test/scaffold-extension.ts && bun run test/scaffold-desktop.ts && bun run test/scaffold-mobile.ts && bun run test/describe.ts && bun run test/picker.ts",
|
|
42
43
|
"test:parts": "bun run test/scaffold-parts.ts",
|
|
43
44
|
"test:pm": "bun run test/scaffold-pm.ts",
|
|
44
45
|
"test:runtime": "bun run test/scaffold-runtime.ts"
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { signInClient } from "@dapplelight/signet-server/auth/client-login" // @mobile
|
|
1
2
|
import { requireStoredSession } from "@dapplelight/signet-server/auth/hono"
|
|
2
3
|
import {
|
|
3
4
|
maskPhone,
|
|
@@ -63,6 +64,10 @@ export function requireUser(s: Services): MiddlewareHandler<AppEnv> {
|
|
|
63
64
|
*
|
|
64
65
|
* POST /otp { phone } sends a code (printed to the console in development)
|
|
65
66
|
* POST /verify { phone, code } sets the session cookie, returns the user
|
|
67
|
+
// mobile:begin
|
|
68
|
+
* POST /verify?client_id=mobile no cookie: returns the user and a token
|
|
69
|
+
* pair (refresh and revoke in routes/mobile.ts)
|
|
70
|
+
// mobile:end
|
|
66
71
|
* POST /sign-out revokes this session
|
|
67
72
|
*/
|
|
68
73
|
export const authRoutes = (s: Services) =>
|
|
@@ -83,6 +88,12 @@ export const authRoutes = (s: Services) =>
|
|
|
83
88
|
zValidator("json", z.object({ phone: z.string().min(6).max(20), code: z.string().min(4) })),
|
|
84
89
|
async (c) => {
|
|
85
90
|
const { phone, code } = c.req.valid("json")
|
|
91
|
+
// mobile:begin
|
|
92
|
+
// Checked before the code, so a typo here does not use it up.
|
|
93
|
+
const clientId = c.req.query("client_id")
|
|
94
|
+
if (clientId !== undefined && !s.clientLogin.clients[clientId])
|
|
95
|
+
throw new ApiException(400, "Unknown client.", "VALIDATION_FAILED")
|
|
96
|
+
// mobile:end
|
|
86
97
|
const r = await verifyPhoneOtp(s.otp, { phone, code, ip: clientIp(c, TRUST) })
|
|
87
98
|
if (!r.ok) throw new ApiException(400, VERIFY_ERRORS[r.code], r.code)
|
|
88
99
|
|
|
@@ -105,13 +116,6 @@ export const authRoutes = (s: Services) =>
|
|
|
105
116
|
.returning()
|
|
106
117
|
.get()
|
|
107
118
|
if (!user) throw new Error("Could not create the account.")
|
|
108
|
-
|
|
109
|
-
const { token } = await startSession(s.sessions, {
|
|
110
|
-
sub: user.id,
|
|
111
|
-
userAgent: c.req.header("user-agent"),
|
|
112
|
-
previousToken: readSessionCookie(c.req.header("cookie"), s.sessions),
|
|
113
|
-
})
|
|
114
|
-
c.header("Set-Cookie", sessionCookie(token, s.sessions))
|
|
115
119
|
// orgs:begin
|
|
116
120
|
// Everyone has an org: a personal one on first sign-in (or for an
|
|
117
121
|
// account from before orgs). Sign-in lands in the first one.
|
|
@@ -119,9 +123,28 @@ export const authRoutes = (s: Services) =>
|
|
|
119
123
|
const org =
|
|
120
124
|
mine[0]?.org ??
|
|
121
125
|
(await s.orgs.create({ name: "Personal", ownerId: user.id, personal: true }))
|
|
122
|
-
c.header("Set-Cookie", orgCookie(org.id, s.orgCookie), { append: true })
|
|
123
126
|
// orgs:end
|
|
124
127
|
if (isNew) await s.notifier.notify(user.id, "account.welcome", { name: maskPhone(r.phone) }) // @notifications
|
|
128
|
+
// mobile:begin
|
|
129
|
+
// The mobile app has no cookie jar: a token pair for the phone's secure
|
|
130
|
+
// store instead, refreshed at /api/mobile/token. // @!orgs
|
|
131
|
+
// store instead, refreshed at /api/mobile/token. It picks an org with // @orgs
|
|
132
|
+
// the x-org header. // @orgs
|
|
133
|
+
if (clientId !== undefined) {
|
|
134
|
+
const tokens = await signInClient(s.clientLogin, user.id, clientId, {
|
|
135
|
+
userAgent: c.req.header("user-agent"),
|
|
136
|
+
ip: clientIp(c, TRUST),
|
|
137
|
+
})
|
|
138
|
+
return c.json({ user: publicUser(user), tokens })
|
|
139
|
+
}
|
|
140
|
+
// mobile:end
|
|
141
|
+
const { token } = await startSession(s.sessions, {
|
|
142
|
+
sub: user.id,
|
|
143
|
+
userAgent: c.req.header("user-agent"),
|
|
144
|
+
previousToken: readSessionCookie(c.req.header("cookie"), s.sessions),
|
|
145
|
+
})
|
|
146
|
+
c.header("Set-Cookie", sessionCookie(token, s.sessions))
|
|
147
|
+
c.header("Set-Cookie", orgCookie(org.id, s.orgCookie), { append: true }) // @orgs
|
|
125
148
|
return c.json({ user: publicUser(user) })
|
|
126
149
|
},
|
|
127
150
|
)
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import { exchangeToken, revokeClientToken } from "@dapplelight/signet-server/auth/client-login"
|
|
2
|
+
import { ApiException } from "@dapplelight/signet-server/http"
|
|
3
|
+
import { zValidator } from "@dapplelight/signet-server/http/validate"
|
|
4
|
+
import { clientIp } from "@dapplelight/signet-server/middleware/rate-limit"
|
|
5
|
+
import { type Context, Hono } from "hono"
|
|
6
|
+
import { z } from "zod"
|
|
7
|
+
import type { AppEnv } from "../app.ts"
|
|
8
|
+
import { type Services, TRUST } from "../services.ts"
|
|
9
|
+
|
|
10
|
+
/** An Expo push token, as `getExpoPushTokenAsync` returns it. */
|
|
11
|
+
const pushToken = z.object({ token: z.string().regex(/^Expo(nent)?PushToken\[[^\]]+\]$/) })
|
|
12
|
+
|
|
13
|
+
/** A form or JSON body's string fields: the token endpoint takes either, as OAuth does. */
|
|
14
|
+
async function params(c: Context): Promise<Record<string, string>> {
|
|
15
|
+
const json = (c.req.header("content-type") ?? "").includes("application/json")
|
|
16
|
+
const body = (json ? await c.req.json().catch(() => ({})) : await c.req.parseBody()) as Record<
|
|
17
|
+
string,
|
|
18
|
+
unknown
|
|
19
|
+
>
|
|
20
|
+
return Object.fromEntries(
|
|
21
|
+
Object.entries(body ?? {}).filter((e): e is [string, string] => typeof e[1] === "string"),
|
|
22
|
+
)
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* The mobile app's routes. Sign-in is POST /api/auth/verify?client_id=mobile,
|
|
27
|
+
* which answers with a token pair instead of the cookie.
|
|
28
|
+
*
|
|
29
|
+
* POST /token grant_type=refresh_token, refresh_token, client_id → new tokens
|
|
30
|
+
* POST /revoke { token } signs this phone out (always 200)
|
|
31
|
+
* POST /push/token { token } saves this phone's Expo push token
|
|
32
|
+
* DELETE /push/token { token } forgets it (sign-out, notifications off)
|
|
33
|
+
* POST /push/test sends yourself a push that opens the Devices tab
|
|
34
|
+
*/
|
|
35
|
+
export const mobileRoutes = (s: Services) =>
|
|
36
|
+
new Hono<AppEnv>()
|
|
37
|
+
.post("/token", async (c) => {
|
|
38
|
+
c.header("Cache-Control", "no-store")
|
|
39
|
+
const p = await params(c)
|
|
40
|
+
// Refresh only: the code and device grants are never issued here.
|
|
41
|
+
if (p.grant_type !== "refresh_token") return c.json({ error: "unsupported_grant_type" }, 400)
|
|
42
|
+
const r = await exchangeToken(s.clientLogin, p, {
|
|
43
|
+
userAgent: c.req.header("user-agent"),
|
|
44
|
+
ip: clientIp(c, TRUST),
|
|
45
|
+
})
|
|
46
|
+
if (!r.ok) return c.json({ error: r.error, error_description: r.error_description }, r.status)
|
|
47
|
+
return c.json(r.tokens)
|
|
48
|
+
})
|
|
49
|
+
.post("/revoke", async (c) => {
|
|
50
|
+
await revokeClientToken(s.clientLogin, (await params(c)).token ?? "")
|
|
51
|
+
return c.json({ ok: true })
|
|
52
|
+
})
|
|
53
|
+
.post("/push/token", zValidator("json", pushToken), async (c) => {
|
|
54
|
+
await s.pushTokens.add(c.get("user").id, c.req.valid("json").token)
|
|
55
|
+
return c.json({ ok: true })
|
|
56
|
+
})
|
|
57
|
+
.delete("/push/token", zValidator("json", pushToken), async (c) => {
|
|
58
|
+
await s.pushTokens.remove(c.req.valid("json").token, c.get("user").id)
|
|
59
|
+
return c.json({ ok: true })
|
|
60
|
+
})
|
|
61
|
+
.post("/push/test", async (c) => {
|
|
62
|
+
const user = c.get("user")
|
|
63
|
+
if (!(await s.pushTokens.list(user.id)).length)
|
|
64
|
+
throw new ApiException(409, "Turn on notifications in the app first.", "CONFLICT")
|
|
65
|
+
const r = await s.push.send(
|
|
66
|
+
user.id,
|
|
67
|
+
{ title: "Test notification", body: "Tap to open your devices.", url: "/devices" },
|
|
68
|
+
{ idempotencyKey: crypto.randomUUID() },
|
|
69
|
+
)
|
|
70
|
+
return c.json({ ok: true, id: r.id })
|
|
71
|
+
})
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { expect, test } from "bun:test"
|
|
2
|
+
import { app, codes, db, post, sqlKv } from "./helpers.ts"
|
|
3
|
+
|
|
4
|
+
type Tokens = { access_token: string; refresh_token: string; expires_in: number }
|
|
5
|
+
|
|
6
|
+
let n = 0
|
|
7
|
+
/** The mobile app's sign-in: the same phone code, answered with a token pair. */
|
|
8
|
+
async function mobileSignIn(phone: string): Promise<Tokens> {
|
|
9
|
+
expect((await post("/api/auth/otp", { phone }, "", `10.1.0.${++n}`)).status).toBe(200)
|
|
10
|
+
const res = await post("/api/auth/verify?client_id=mobile", { phone, code: codes.get(phone) })
|
|
11
|
+
expect(res.status).toBe(200)
|
|
12
|
+
expect(res.headers.get("set-cookie")).toBeNull()
|
|
13
|
+
return ((await res.json()) as { tokens: Tokens }).tokens
|
|
14
|
+
}
|
|
15
|
+
const bearer = (token: string, init: RequestInit = {}) => ({
|
|
16
|
+
...init,
|
|
17
|
+
headers: { "content-type": "application/json", authorization: `Bearer ${token}` },
|
|
18
|
+
})
|
|
19
|
+
const form = (body: Record<string, string>) =>
|
|
20
|
+
app.request("/api/mobile/token", {
|
|
21
|
+
method: "POST",
|
|
22
|
+
headers: { "content-type": "application/x-www-form-urlencoded" },
|
|
23
|
+
body: new URLSearchParams(body).toString(),
|
|
24
|
+
})
|
|
25
|
+
|
|
26
|
+
test("an unknown client is refused before the code is used", async () => {
|
|
27
|
+
await post("/api/auth/otp", { phone: "+919000000701" }, "", "10.1.1.1")
|
|
28
|
+
const bad = await post("/api/auth/verify?client_id=other", {
|
|
29
|
+
phone: "+919000000701",
|
|
30
|
+
code: codes.get("+919000000701"),
|
|
31
|
+
})
|
|
32
|
+
expect(bad.status).toBe(400)
|
|
33
|
+
})
|
|
34
|
+
|
|
35
|
+
test("sign in, call the API with the token, refresh with a form post", async () => {
|
|
36
|
+
const t = await mobileSignIn("+919000000702")
|
|
37
|
+
expect((await app.request("/api/account/me", bearer(t.access_token))).status).toBe(200)
|
|
38
|
+
const res = await form({
|
|
39
|
+
grant_type: "refresh_token",
|
|
40
|
+
refresh_token: t.refresh_token,
|
|
41
|
+
client_id: "mobile",
|
|
42
|
+
})
|
|
43
|
+
expect(res.status).toBe(200)
|
|
44
|
+
const next = (await res.json()) as Tokens
|
|
45
|
+
expect((await app.request("/api/account/me", bearer(next.access_token))).status).toBe(200)
|
|
46
|
+
// A refresh token works once; the old one again revokes the session.
|
|
47
|
+
const again = await form({
|
|
48
|
+
grant_type: "refresh_token",
|
|
49
|
+
refresh_token: t.refresh_token,
|
|
50
|
+
client_id: "mobile",
|
|
51
|
+
})
|
|
52
|
+
expect(again.status).toBe(400)
|
|
53
|
+
})
|
|
54
|
+
|
|
55
|
+
test("the devices list sees the phone's session", async () => {
|
|
56
|
+
const t = await mobileSignIn("+919000000703")
|
|
57
|
+
const res = await app.request("/api/sessions", bearer(t.access_token))
|
|
58
|
+
const { sessions } = (await res.json()) as { sessions: { current: boolean }[] }
|
|
59
|
+
expect(sessions.some((s) => s.current)).toBe(true)
|
|
60
|
+
})
|
|
61
|
+
|
|
62
|
+
test("push tokens: saved, refused when malformed, and revoke signs out", async () => {
|
|
63
|
+
const t = await mobileSignIn("+919000000704")
|
|
64
|
+
const save = (token: string) =>
|
|
65
|
+
app.request(
|
|
66
|
+
"/api/mobile/push/token",
|
|
67
|
+
bearer(t.access_token, { method: "POST", body: JSON.stringify({ token }) }),
|
|
68
|
+
)
|
|
69
|
+
expect((await save("ExponentPushToken[abc123]")).status).toBe(200)
|
|
70
|
+
expect((await save("not-a-token")).status).toBe(400)
|
|
71
|
+
const anonymous = await post("/api/mobile/push/token", { token: "ExponentPushToken[x]" })
|
|
72
|
+
expect(anonymous.status).toBe(401)
|
|
73
|
+
|
|
74
|
+
await app.request("/api/mobile/revoke", {
|
|
75
|
+
method: "POST",
|
|
76
|
+
headers: { "content-type": "application/x-www-form-urlencoded" },
|
|
77
|
+
body: new URLSearchParams({ token: t.refresh_token }).toString(),
|
|
78
|
+
})
|
|
79
|
+
expect((await app.request("/api/account/me", bearer(t.access_token))).status).toBe(401)
|
|
80
|
+
})
|
|
81
|
+
|
|
82
|
+
test("a phone's push token follows the account that last turned push on", async () => {
|
|
83
|
+
const kv = sqlKv(db.orm)
|
|
84
|
+
const token = "ExponentPushToken[shared-phone]"
|
|
85
|
+
const turnOn = async (phone: string) => {
|
|
86
|
+
const t = await mobileSignIn(phone)
|
|
87
|
+
const me = await app.request("/api/account/me", bearer(t.access_token))
|
|
88
|
+
const { user } = (await me.json()) as { user: { id: string } }
|
|
89
|
+
const res = await app.request(
|
|
90
|
+
"/api/mobile/push/token",
|
|
91
|
+
bearer(t.access_token, { method: "POST", body: JSON.stringify({ token }) }),
|
|
92
|
+
)
|
|
93
|
+
expect(res.status).toBe(200)
|
|
94
|
+
return user.id
|
|
95
|
+
}
|
|
96
|
+
const tokensOf = async (id: string) =>
|
|
97
|
+
JSON.parse((await kv.get(`push-tokens:${id}`)) ?? "[]") as string[]
|
|
98
|
+
|
|
99
|
+
// A never signs out on the server (offline sign-out), then B uses the phone.
|
|
100
|
+
const a = await turnOn("+919000000705")
|
|
101
|
+
const b = await turnOn("+919000000706")
|
|
102
|
+
expect(await tokensOf(a)).toEqual([])
|
|
103
|
+
expect(await tokensOf(b)).toEqual([token])
|
|
104
|
+
})
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { Part } from "../../src/compose.js"
|
|
2
|
+
|
|
3
|
+
export default {
|
|
4
|
+
description: "the mobile app's API: token sign-in, refresh, Expo push tokens",
|
|
5
|
+
needs: ["auth"],
|
|
6
|
+
apiOnly: true,
|
|
7
|
+
env: () => [
|
|
8
|
+
"# Expo push: an access token, once push security is on in your Expo project.",
|
|
9
|
+
"EXPO_ACCESS_TOKEN=",
|
|
10
|
+
],
|
|
11
|
+
} satisfies Part
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
@@ -6,5 +6,15 @@
|
|
|
6
6
|
"display": "standalone",
|
|
7
7
|
"background_color": "#ffffff",
|
|
8
8
|
"theme_color": "#ffffff",
|
|
9
|
-
"icons": [
|
|
9
|
+
"icons": [
|
|
10
|
+
{ "src": "/icon.svg", "sizes": "any", "type": "image/svg+xml", "purpose": "any" },
|
|
11
|
+
{ "src": "/icon-192.png", "sizes": "192x192", "type": "image/png", "purpose": "any" },
|
|
12
|
+
{ "src": "/icon-512.png", "sizes": "512x512", "type": "image/png", "purpose": "any" },
|
|
13
|
+
{
|
|
14
|
+
"src": "/icon-maskable-512.png",
|
|
15
|
+
"sizes": "512x512",
|
|
16
|
+
"type": "image/png",
|
|
17
|
+
"purpose": "maskable"
|
|
18
|
+
}
|
|
19
|
+
]
|
|
10
20
|
}
|
|
@@ -15,7 +15,14 @@ async function cacheShell() {
|
|
|
15
15
|
const html = await res.clone().text()
|
|
16
16
|
const assets = [...html.matchAll(/\/assets\/[^"'\s]+/g)].map((m) => m[0])
|
|
17
17
|
await cache.put("/", res)
|
|
18
|
-
await cache.addAll([
|
|
18
|
+
await cache.addAll([
|
|
19
|
+
"/manifest.webmanifest",
|
|
20
|
+
"/icon.svg",
|
|
21
|
+
"/icon-192.png",
|
|
22
|
+
"/icon-512.png",
|
|
23
|
+
"/icon-maskable-512.png",
|
|
24
|
+
...new Set(assets),
|
|
25
|
+
])
|
|
19
26
|
}
|
|
20
27
|
|
|
21
28
|
self.addEventListener("install", (event) => {
|
package/src/compose.ts
CHANGED
|
@@ -21,6 +21,7 @@ import auth from "../parts/auth/part.js"
|
|
|
21
21
|
import dashboard from "../parts/dashboard/part.js"
|
|
22
22
|
import growth from "../parts/growth/part.js"
|
|
23
23
|
import mcp from "../parts/mcp/part.js"
|
|
24
|
+
import mobile from "../parts/mobile/part.js"
|
|
24
25
|
import notifications from "../parts/notifications/part.js"
|
|
25
26
|
import orgs from "../parts/orgs/part.js"
|
|
26
27
|
import payments from "../parts/payments/part.js"
|
|
@@ -71,6 +72,7 @@ export const PART_NAMES = [
|
|
|
71
72
|
"workflows",
|
|
72
73
|
"dashboard",
|
|
73
74
|
"pwa",
|
|
75
|
+
"mobile",
|
|
74
76
|
"mcp",
|
|
75
77
|
] as const
|
|
76
78
|
export type PartName = (typeof PART_NAMES)[number]
|
|
@@ -88,15 +90,17 @@ export const PARTS: Record<PartName, Part> = {
|
|
|
88
90
|
workflows,
|
|
89
91
|
dashboard,
|
|
90
92
|
pwa,
|
|
93
|
+
mobile,
|
|
91
94
|
mcp,
|
|
92
95
|
}
|
|
93
96
|
|
|
94
97
|
/**
|
|
95
98
|
* A named mix of parts, by the shape of app, never its domain. `full` is
|
|
96
99
|
* everything the full template had (not dashboard or pwa, which reshape the
|
|
97
|
-
* web half); `blank` is the base alone (the shell, the
|
|
100
|
+
* web half, nor mobile, which serves a phone app); `blank` is the base alone (the shell, the
|
|
98
101
|
* API, the database), for parts of your own. Needs are added for you (admin
|
|
99
|
-
* brings orgs, everything brings auth). `surface: "api"` is the API half only
|
|
102
|
+
* brings orgs, everything brings auth). `surface: "api"` is the API half only;
|
|
103
|
+
* `surface: "mobile"` is an Expo app in mobile/ with the API half in server/.
|
|
100
104
|
* MCP is not listed: it is asked for (or --mcp / --no-mcp), as it always was.
|
|
101
105
|
* Each description is one line, quoted, first: signet-mcp's index reads it.
|
|
102
106
|
* The label is the picker's row, in words for someone who knows none of the
|
|
@@ -106,7 +110,7 @@ export const STARTERS = {
|
|
|
106
110
|
full: {
|
|
107
111
|
description: "every part, web + API",
|
|
108
112
|
label: "Everything — every feature",
|
|
109
|
-
parts: PART_NAMES.filter((p) => !["mcp", "dashboard", "pwa"].includes(p)),
|
|
113
|
+
parts: PART_NAMES.filter((p) => !["mcp", "dashboard", "pwa", "mobile"].includes(p)),
|
|
110
114
|
},
|
|
111
115
|
blank: {
|
|
112
116
|
description: "no parts: the shell, the API and the database",
|
|
@@ -159,9 +163,15 @@ export const STARTERS = {
|
|
|
159
163
|
label: "Installable app — works offline",
|
|
160
164
|
parts: ["account", "pwa"],
|
|
161
165
|
},
|
|
166
|
+
mobile: {
|
|
167
|
+
description: "an Expo app for iOS and Android and its API: phone sign-in, push, offline",
|
|
168
|
+
label: "Mobile app — iOS and Android, with its API",
|
|
169
|
+
parts: ["account", "mobile"],
|
|
170
|
+
surface: "mobile",
|
|
171
|
+
},
|
|
162
172
|
} satisfies Record<
|
|
163
173
|
string,
|
|
164
|
-
{ description: string; label: string; parts: PartName[]; surface?: "api" }
|
|
174
|
+
{ description: string; label: string; parts: PartName[]; surface?: "api" | "mobile" }
|
|
165
175
|
>
|
|
166
176
|
export type StarterName = keyof typeof STARTERS
|
|
167
177
|
|
|
@@ -376,6 +386,7 @@ export async function compose(
|
|
|
376
386
|
|
|
377
387
|
const on = new Set<string>([...parts, ...(web ? ["web"] : []), ...(api ? ["api", runtime] : [])])
|
|
378
388
|
for (const f of await walk(dest)) {
|
|
389
|
+
if (f.endsWith(".png")) continue // binary: never round-trip through utf8
|
|
379
390
|
const path = join(dest, f)
|
|
380
391
|
const text = await readFile(path, "utf8")
|
|
381
392
|
let out = applyBlocks(text, on)
|