create-expo-updates-server 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +19 -0
- package/bin/create-expo-updates-server.mjs +5 -0
- package/dist/template/.env.docker.example +15 -0
- package/dist/template/.env.example +35 -0
- package/dist/template/Dockerfile +42 -0
- package/dist/template/LICENSE +21 -0
- package/dist/template/README.md +665 -0
- package/dist/template/app/api/admin/access-tokens/[id]/route.ts +25 -0
- package/dist/template/app/api/admin/access-tokens/route.test.ts +73 -0
- package/dist/template/app/api/admin/access-tokens/route.ts +90 -0
- package/dist/template/app/api/admin/embedded-updates/[embeddedUpdateId]/route.ts +25 -0
- package/dist/template/app/api/admin/embedded-updates/route.test.ts +102 -0
- package/dist/template/app/api/admin/embedded-updates/route.ts +47 -0
- package/dist/template/app/api/admin/emergency-redirects/[id]/route.ts +62 -0
- package/dist/template/app/api/admin/emergency-redirects/route.test.ts +84 -0
- package/dist/template/app/api/admin/emergency-redirects/route.ts +56 -0
- package/dist/template/app/api/admin/login/route.test.ts +55 -0
- package/dist/template/app/api/admin/login/route.ts +52 -0
- package/dist/template/app/api/admin/logout/route.ts +20 -0
- package/dist/template/app/api/admin/session/route.ts +15 -0
- package/dist/template/app/api/admin/updates/[encodedKey]/deactivate/route.ts +33 -0
- package/dist/template/app/api/admin/updates/[encodedKey]/promote/route.ts +29 -0
- package/dist/template/app/api/admin/updates/[encodedKey]/rollback/route.ts +29 -0
- package/dist/template/app/api/admin/updates/[encodedKey]/route.ts +96 -0
- package/dist/template/app/api/admin/updates/route.test.ts +142 -0
- package/dist/template/app/api/admin/updates/route.ts +32 -0
- package/dist/template/app/api/assets/route.ts +6 -0
- package/dist/template/app/api/health/route.test.ts +26 -0
- package/dist/template/app/api/health/route.ts +42 -0
- package/dist/template/app/api/manifest/route.ts +6 -0
- package/dist/template/app/api/update-complete/route.ts +6 -0
- package/dist/template/app/favicon.ico +0 -0
- package/dist/template/app/globals.css +26 -0
- package/dist/template/app/layout.tsx +34 -0
- package/dist/template/app/login/page.tsx +77 -0
- package/dist/template/app/page.tsx +12 -0
- package/dist/template/app/updates/[encodedKey]/page.tsx +482 -0
- package/dist/template/app/updates/embedded/page.tsx +164 -0
- package/dist/template/app/updates/emergency-redirects/page.tsx +430 -0
- package/dist/template/app/updates/layout.tsx +14 -0
- package/dist/template/app/updates/page.tsx +281 -0
- package/dist/template/docker-compose.yml +100 -0
- package/dist/template/docs/expo-app-setup.md +497 -0
- package/dist/template/docs/getting-started.md +502 -0
- package/dist/template/docs/getting-started.ru.md +623 -0
- package/dist/template/docs/index.md +57 -0
- package/dist/template/docs/migrations/schema.sql +363 -0
- package/dist/template/docs/npm-installer.md +83 -0
- package/dist/template/docs/operations-guide.md +270 -0
- package/dist/template/docs/ota-emergency-recovery.md +109 -0
- package/dist/template/docs/supabase-setup.md +133 -0
- package/dist/template/eslint.config.mjs +30 -0
- package/dist/template/gitignore.template +58 -0
- package/dist/template/next.config.ts +7 -0
- package/dist/template/package-lock.json +12156 -0
- package/dist/template/package.json +50 -0
- package/dist/template/postcss.config.mjs +7 -0
- package/dist/template/public/file.svg +1 -0
- package/dist/template/public/globe.svg +1 -0
- package/dist/template/public/next.svg +1 -0
- package/dist/template/public/vercel.svg +1 -0
- package/dist/template/public/window.svg +1 -0
- package/dist/template/scripts/configure-expo-app.mjs +145 -0
- package/dist/template/scripts/create-access-token.mjs +135 -0
- package/dist/template/scripts/create-admin.mjs +169 -0
- package/dist/template/scripts/import-emergency-redirects.mjs +126 -0
- package/dist/template/scripts/lib/embedded-update-registrar.test.ts +64 -0
- package/dist/template/scripts/lib/expo-app-configurator.mjs +666 -0
- package/dist/template/scripts/lib/expo-app-configurator.test.ts +463 -0
- package/dist/template/scripts/lib/expo-app-prompts.mjs +139 -0
- package/dist/template/scripts/lib/expo-app-prompts.test.ts +97 -0
- package/dist/template/scripts/lib/expo-export-command.test.ts +31 -0
- package/dist/template/scripts/lib/ota-publish-retry.test.ts +33 -0
- package/dist/template/scripts/manage-emergency-redirect.mjs +483 -0
- package/dist/template/scripts/sync-docker-database-password.sh +16 -0
- package/dist/template/src/client/admin-api.ts +174 -0
- package/dist/template/src/client/admin-types.ts +93 -0
- package/dist/template/src/client/logout-button.tsx +31 -0
- package/dist/template/src/server/controllers/assets.ts +216 -0
- package/dist/template/src/server/controllers/manifest.test.ts +403 -0
- package/dist/template/src/server/controllers/manifest.ts +626 -0
- package/dist/template/src/server/controllers/update-complete.ts +36 -0
- package/dist/template/src/server/lib/admin-access-tokens.ts +169 -0
- package/dist/template/src/server/lib/admin-api.ts +101 -0
- package/dist/template/src/server/lib/admin-auth.ts +208 -0
- package/dist/template/src/server/lib/admin-embedded-updates.ts +150 -0
- package/dist/template/src/server/lib/admin-updates.ts +1282 -0
- package/dist/template/src/server/lib/common.js +24 -0
- package/dist/template/src/server/lib/emergency-channel-redirects.ts +310 -0
- package/dist/template/src/server/lib/env.js +8 -0
- package/dist/template/src/server/lib/manifest-helpers.js +91 -0
- package/dist/template/src/server/lib/response.js +11 -0
- package/dist/template/src/server/lib/signing.js +55 -0
- package/dist/template/src/server/lib/supabase.js +763 -0
- package/dist/template/src/server/manifest/manifest-repository.ts +269 -0
- package/dist/template/src/server/manifest/manifest-request.ts +21 -0
- package/dist/template/src/server/manifest/manifest-response.ts +235 -0
- package/dist/template/src/server/manifest/manifest-values.ts +62 -0
- package/dist/template/templates/expo-app/.env.ota.example +18 -0
- package/dist/template/templates/expo-app/ci_scripts/ci_post_xcodebuild.sh +6 -0
- package/dist/template/templates/expo-app/ci_scripts/register-embedded-update.sh +36 -0
- package/dist/template/templates/expo-app/plugins/with-ota-embedded-registration.js +33 -0
- package/dist/template/templates/expo-app/scripts/ota-publish/api/database-client.mjs +87 -0
- package/dist/template/templates/expo-app/scripts/ota-publish/api/storage-client.mjs +57 -0
- package/dist/template/templates/expo-app/scripts/ota-publish/index.mjs +182 -0
- package/dist/template/templates/expo-app/scripts/ota-publish/lib/common.mjs +84 -0
- package/dist/template/templates/expo-app/scripts/ota-publish/lib/expo-export-command.mjs +24 -0
- package/dist/template/templates/expo-app/scripts/ota-publish/lib/retry.mjs +25 -0
- package/dist/template/templates/expo-app/scripts/ota-publish/shared/config.mjs +48 -0
- package/dist/template/templates/expo-app/scripts/ota-register-embedded/android-register-embedded-update.sh +18 -0
- package/dist/template/templates/expo-app/scripts/ota-register-embedded/index.mjs +275 -0
- package/dist/template/tsconfig.json +36 -0
- package/dist/template/vitest.config.mts +20 -0
- package/dist/template-manifest.json +564 -0
- package/lib/cli.mjs +549 -0
- package/package.json +41 -0
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
import { createHash, randomBytes, randomUUID } from "node:crypto";
|
|
2
|
+
import { supabase } from "./supabase.js";
|
|
3
|
+
|
|
4
|
+
export const ACCESS_TOKEN_SCOPES = [
|
|
5
|
+
"updates:read",
|
|
6
|
+
"updates:write",
|
|
7
|
+
"redirects:read",
|
|
8
|
+
"redirects:write",
|
|
9
|
+
] as const;
|
|
10
|
+
|
|
11
|
+
export type AccessTokenScope = (typeof ACCESS_TOKEN_SCOPES)[number];
|
|
12
|
+
|
|
13
|
+
export type AuthenticatedAccessToken = {
|
|
14
|
+
id: string;
|
|
15
|
+
name: string;
|
|
16
|
+
scopes: AccessTokenScope[];
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
type AccessTokenRow = {
|
|
20
|
+
id: string;
|
|
21
|
+
name: string;
|
|
22
|
+
token_prefix: string;
|
|
23
|
+
token_hash: string;
|
|
24
|
+
scopes: AccessTokenScope[];
|
|
25
|
+
expires_at: string | null;
|
|
26
|
+
revoked_at: string | null;
|
|
27
|
+
last_used_at: string | null;
|
|
28
|
+
created_at: string;
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
function hashToken(token: string): string {
|
|
32
|
+
return createHash("sha256").update(token, "utf8").digest("hex");
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export type AccessTokenRecord = {
|
|
36
|
+
id: string;
|
|
37
|
+
name: string;
|
|
38
|
+
tokenPrefix: string;
|
|
39
|
+
scopes: AccessTokenScope[];
|
|
40
|
+
expiresAt: string | null;
|
|
41
|
+
revokedAt: string | null;
|
|
42
|
+
lastUsedAt: string | null;
|
|
43
|
+
createdAt: string;
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
function mapAccessToken(row: AccessTokenRow): AccessTokenRecord {
|
|
47
|
+
return {
|
|
48
|
+
id: row.id,
|
|
49
|
+
name: row.name,
|
|
50
|
+
tokenPrefix: row.token_prefix,
|
|
51
|
+
scopes: row.scopes,
|
|
52
|
+
expiresAt: row.expires_at,
|
|
53
|
+
revokedAt: row.revoked_at,
|
|
54
|
+
lastUsedAt: row.last_used_at,
|
|
55
|
+
createdAt: row.created_at,
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function isAccessTokenScope(value: unknown): value is AccessTokenScope {
|
|
60
|
+
return (
|
|
61
|
+
typeof value === "string" &&
|
|
62
|
+
ACCESS_TOKEN_SCOPES.includes(value as AccessTokenScope)
|
|
63
|
+
);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export async function createAccessToken(input: {
|
|
67
|
+
name: string;
|
|
68
|
+
scopes: AccessTokenScope[];
|
|
69
|
+
expiresAt?: string | null;
|
|
70
|
+
}): Promise<{ token: string; tokenRecord: AccessTokenRecord }> {
|
|
71
|
+
const token = `ota_${randomBytes(32).toString("base64url")}`;
|
|
72
|
+
const now = new Date().toISOString();
|
|
73
|
+
const row: AccessTokenRow = {
|
|
74
|
+
id: randomUUID(),
|
|
75
|
+
name: input.name,
|
|
76
|
+
token_prefix: token.slice(0, 12),
|
|
77
|
+
token_hash: hashToken(token),
|
|
78
|
+
scopes: input.scopes,
|
|
79
|
+
expires_at: input.expiresAt || null,
|
|
80
|
+
revoked_at: null,
|
|
81
|
+
last_used_at: null,
|
|
82
|
+
created_at: now,
|
|
83
|
+
};
|
|
84
|
+
|
|
85
|
+
const { data, error } = await supabase
|
|
86
|
+
.from("ota_access_tokens")
|
|
87
|
+
.upsert(row, { onConflict: "id" })
|
|
88
|
+
.select("*")
|
|
89
|
+
.single();
|
|
90
|
+
|
|
91
|
+
if (error || !data) {
|
|
92
|
+
throw new Error(`Failed to create access token: ${error?.message}`);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
return {
|
|
96
|
+
token,
|
|
97
|
+
tokenRecord: mapAccessToken(data as AccessTokenRow),
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export async function listAccessTokens(): Promise<AccessTokenRecord[]> {
|
|
102
|
+
const { data, error } = await supabase
|
|
103
|
+
.from("ota_access_tokens")
|
|
104
|
+
.select(
|
|
105
|
+
"id,name,token_prefix,scopes,expires_at,revoked_at,last_used_at,created_at",
|
|
106
|
+
)
|
|
107
|
+
.order("created_at", { ascending: false })
|
|
108
|
+
.execute();
|
|
109
|
+
|
|
110
|
+
if (error) {
|
|
111
|
+
throw new Error(`Failed to list access tokens: ${error.message}`);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
return ((data || []) as AccessTokenRow[]).map(mapAccessToken);
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export async function revokeAccessToken(id: string): Promise<void> {
|
|
118
|
+
const { error } = await supabase
|
|
119
|
+
.from("ota_access_tokens")
|
|
120
|
+
.update({ revoked_at: new Date().toISOString() })
|
|
121
|
+
.eq("id", id)
|
|
122
|
+
.execute();
|
|
123
|
+
|
|
124
|
+
if (error) {
|
|
125
|
+
throw new Error(`Failed to revoke access token: ${error.message}`);
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export async function authenticateAccessToken(
|
|
130
|
+
token: string,
|
|
131
|
+
): Promise<AuthenticatedAccessToken | null> {
|
|
132
|
+
if (!token.startsWith("ota_")) {
|
|
133
|
+
return null;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
const { data, error } = await supabase
|
|
137
|
+
.from("ota_access_tokens")
|
|
138
|
+
.select(
|
|
139
|
+
"id,name,token_prefix,token_hash,scopes,expires_at,revoked_at,last_used_at,created_at",
|
|
140
|
+
)
|
|
141
|
+
.eq("token_hash", hashToken(token))
|
|
142
|
+
.maybeSingle();
|
|
143
|
+
|
|
144
|
+
if (error || !data) {
|
|
145
|
+
return null;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
const row = data as AccessTokenRow;
|
|
149
|
+
if (row.revoked_at) {
|
|
150
|
+
return null;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
if (row.expires_at && Date.parse(row.expires_at) <= Date.now()) {
|
|
154
|
+
return null;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
const lastUsedUpdate = supabase
|
|
158
|
+
.from("ota_access_tokens")
|
|
159
|
+
.update({ last_used_at: new Date().toISOString() })
|
|
160
|
+
.eq("id", row.id)
|
|
161
|
+
.execute();
|
|
162
|
+
void Promise.resolve(lastUsedUpdate).catch(() => undefined);
|
|
163
|
+
|
|
164
|
+
return {
|
|
165
|
+
id: row.id,
|
|
166
|
+
name: row.name,
|
|
167
|
+
scopes: row.scopes,
|
|
168
|
+
};
|
|
169
|
+
}
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import {
|
|
2
|
+
AdminRole,
|
|
3
|
+
getAdminSessionFromRequest,
|
|
4
|
+
} from "@/src/server/lib/admin-auth";
|
|
5
|
+
import {
|
|
6
|
+
AccessTokenScope,
|
|
7
|
+
authenticateAccessToken,
|
|
8
|
+
} from "@/src/server/lib/admin-access-tokens";
|
|
9
|
+
import { NextRequest, NextResponse } from "next/server";
|
|
10
|
+
|
|
11
|
+
export type AdminPrincipal =
|
|
12
|
+
| { type: "session"; id: string; username: string; role: AdminRole }
|
|
13
|
+
| { type: "access-token"; id: string; name: string; scopes: string[] };
|
|
14
|
+
|
|
15
|
+
function getBearerToken(request: NextRequest): string | null {
|
|
16
|
+
const authorization = request.headers.get("authorization");
|
|
17
|
+
if (!authorization) {
|
|
18
|
+
return null;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
const match = authorization.match(/^Bearer\s+(.+)$/i);
|
|
22
|
+
return match?.[1]?.trim() || null;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const ROLE_SCOPES: Record<AdminRole, AccessTokenScope[]> = {
|
|
26
|
+
admin: [
|
|
27
|
+
"updates:read",
|
|
28
|
+
"updates:write",
|
|
29
|
+
"redirects:read",
|
|
30
|
+
"redirects:write",
|
|
31
|
+
],
|
|
32
|
+
operator: [
|
|
33
|
+
"updates:read",
|
|
34
|
+
"updates:write",
|
|
35
|
+
"redirects:read",
|
|
36
|
+
"redirects:write",
|
|
37
|
+
],
|
|
38
|
+
viewer: ["updates:read", "redirects:read"],
|
|
39
|
+
};
|
|
40
|
+
|
|
41
|
+
export async function requireAdminSession(
|
|
42
|
+
request: NextRequest,
|
|
43
|
+
allowedRoles: AdminRole[] = ["admin", "operator", "viewer"],
|
|
44
|
+
): Promise<{ id: string; username: string; role: AdminRole } | NextResponse> {
|
|
45
|
+
const session = await getAdminSessionFromRequest(request);
|
|
46
|
+
if (!session) {
|
|
47
|
+
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
if (!allowedRoles.includes(session.role)) {
|
|
51
|
+
return NextResponse.json({ error: "Forbidden" }, { status: 403 });
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
return session;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export async function requireAdminAccess(
|
|
58
|
+
request: NextRequest,
|
|
59
|
+
requiredScope: AccessTokenScope,
|
|
60
|
+
): Promise<AdminPrincipal | NextResponse> {
|
|
61
|
+
const session = await getAdminSessionFromRequest(request);
|
|
62
|
+
if (session) {
|
|
63
|
+
if (!ROLE_SCOPES[session.role].includes(requiredScope)) {
|
|
64
|
+
return NextResponse.json(
|
|
65
|
+
{ error: `Missing required scope: ${requiredScope}` },
|
|
66
|
+
{ status: 403 },
|
|
67
|
+
);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
return {
|
|
71
|
+
type: "session",
|
|
72
|
+
id: session.id,
|
|
73
|
+
username: session.username,
|
|
74
|
+
role: session.role,
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const bearerToken = getBearerToken(request);
|
|
79
|
+
if (!bearerToken) {
|
|
80
|
+
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const accessToken = await authenticateAccessToken(bearerToken);
|
|
84
|
+
if (!accessToken) {
|
|
85
|
+
return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
if (!accessToken.scopes.includes(requiredScope)) {
|
|
89
|
+
return NextResponse.json(
|
|
90
|
+
{ error: `Missing required scope: ${requiredScope}` },
|
|
91
|
+
{ status: 403 },
|
|
92
|
+
);
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
return {
|
|
96
|
+
type: "access-token",
|
|
97
|
+
id: accessToken.id,
|
|
98
|
+
name: accessToken.name,
|
|
99
|
+
scopes: accessToken.scopes,
|
|
100
|
+
};
|
|
101
|
+
}
|
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
import { compare } from "bcryptjs";
|
|
2
|
+
import { createHash, randomBytes, randomUUID } from "node:crypto";
|
|
3
|
+
import { cookies } from "next/headers";
|
|
4
|
+
import { NextRequest } from "next/server";
|
|
5
|
+
import { supabase } from "./supabase.js";
|
|
6
|
+
|
|
7
|
+
export type AdminRole = "admin" | "operator" | "viewer";
|
|
8
|
+
|
|
9
|
+
export type AdminSession = {
|
|
10
|
+
id: string;
|
|
11
|
+
username: string;
|
|
12
|
+
role: AdminRole;
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
type AdminUserRow = {
|
|
16
|
+
id: string;
|
|
17
|
+
username: string;
|
|
18
|
+
password_hash: string;
|
|
19
|
+
role: AdminRole;
|
|
20
|
+
is_active: boolean;
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
type AdminSessionRow = {
|
|
24
|
+
id: string;
|
|
25
|
+
user_id: string;
|
|
26
|
+
token_hash: string;
|
|
27
|
+
expires_at: string;
|
|
28
|
+
revoked_at: string | null;
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
const SESSION_COOKIE_NAME = "ota_admin_session";
|
|
32
|
+
const SESSION_TTL_SECONDS = 60 * 60 * 24 * 7;
|
|
33
|
+
|
|
34
|
+
function hashToken(token: string): string {
|
|
35
|
+
return createHash("sha256").update(token, "utf8").digest("hex");
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function normalizeUsername(username: string): string {
|
|
39
|
+
return username.trim().toLowerCase();
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
async function getActiveUserById(id: string): Promise<AdminUserRow | null> {
|
|
43
|
+
const { data, error } = await supabase
|
|
44
|
+
.from("ota_admin_users")
|
|
45
|
+
.select("id,username,password_hash,role,is_active")
|
|
46
|
+
.eq("id", id)
|
|
47
|
+
.eq("is_active", true)
|
|
48
|
+
.maybeSingle();
|
|
49
|
+
|
|
50
|
+
if (error) {
|
|
51
|
+
throw new Error(`Failed to load admin user: ${error.message}`);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
return (data as AdminUserRow | null) || null;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export async function validateAdminCredentials(
|
|
58
|
+
username: string,
|
|
59
|
+
password: string,
|
|
60
|
+
): Promise<AdminSession | null> {
|
|
61
|
+
if (!username || !password) {
|
|
62
|
+
return null;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const { data, error } = await supabase
|
|
66
|
+
.from("ota_admin_users")
|
|
67
|
+
.select("id,username,password_hash,role,is_active")
|
|
68
|
+
.eq("username", normalizeUsername(username))
|
|
69
|
+
.eq("is_active", true)
|
|
70
|
+
.maybeSingle();
|
|
71
|
+
|
|
72
|
+
if (error) {
|
|
73
|
+
throw new Error(`Failed to validate admin credentials: ${error.message}`);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const user = data as AdminUserRow | null;
|
|
77
|
+
if (!user || !(await compare(password, user.password_hash))) {
|
|
78
|
+
return null;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
const lastLoginUpdate = supabase
|
|
82
|
+
.from("ota_admin_users")
|
|
83
|
+
.update({ last_login_at: new Date().toISOString() })
|
|
84
|
+
.eq("id", user.id)
|
|
85
|
+
.execute();
|
|
86
|
+
void Promise.resolve(lastLoginUpdate).catch(() => undefined);
|
|
87
|
+
|
|
88
|
+
return {
|
|
89
|
+
id: user.id,
|
|
90
|
+
username: user.username,
|
|
91
|
+
role: user.role,
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export async function createAdminSession(
|
|
96
|
+
user: AdminSession,
|
|
97
|
+
): Promise<string> {
|
|
98
|
+
const token = `otas_${randomBytes(32).toString("base64url")}`;
|
|
99
|
+
const now = Date.now();
|
|
100
|
+
const row: AdminSessionRow & {
|
|
101
|
+
created_at: string;
|
|
102
|
+
last_used_at: string;
|
|
103
|
+
} = {
|
|
104
|
+
id: randomUUID(),
|
|
105
|
+
user_id: user.id,
|
|
106
|
+
token_hash: hashToken(token),
|
|
107
|
+
expires_at: new Date(now + SESSION_TTL_SECONDS * 1000).toISOString(),
|
|
108
|
+
revoked_at: null,
|
|
109
|
+
created_at: new Date(now).toISOString(),
|
|
110
|
+
last_used_at: new Date(now).toISOString(),
|
|
111
|
+
};
|
|
112
|
+
|
|
113
|
+
const { error } = await supabase
|
|
114
|
+
.from("ota_admin_sessions")
|
|
115
|
+
.upsert(row, { onConflict: "id" })
|
|
116
|
+
.execute();
|
|
117
|
+
|
|
118
|
+
if (error) {
|
|
119
|
+
throw new Error(`Failed to create admin session: ${error.message}`);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
return token;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
async function authenticateSessionToken(
|
|
126
|
+
token: string | undefined,
|
|
127
|
+
): Promise<AdminSession | null> {
|
|
128
|
+
if (!token?.startsWith("otas_")) {
|
|
129
|
+
return null;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
const { data, error } = await supabase
|
|
133
|
+
.from("ota_admin_sessions")
|
|
134
|
+
.select("id,user_id,token_hash,expires_at,revoked_at")
|
|
135
|
+
.eq("token_hash", hashToken(token))
|
|
136
|
+
.maybeSingle();
|
|
137
|
+
|
|
138
|
+
if (error) {
|
|
139
|
+
throw new Error(`Failed to validate admin session: ${error.message}`);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
const session = data as AdminSessionRow | null;
|
|
143
|
+
if (
|
|
144
|
+
!session ||
|
|
145
|
+
session.revoked_at ||
|
|
146
|
+
Date.parse(session.expires_at) <= Date.now()
|
|
147
|
+
) {
|
|
148
|
+
return null;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
const user = await getActiveUserById(session.user_id);
|
|
152
|
+
if (!user) {
|
|
153
|
+
return null;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
const lastUsedUpdate = supabase
|
|
157
|
+
.from("ota_admin_sessions")
|
|
158
|
+
.update({ last_used_at: new Date().toISOString() })
|
|
159
|
+
.eq("id", session.id)
|
|
160
|
+
.execute();
|
|
161
|
+
void Promise.resolve(lastUsedUpdate).catch(() => undefined);
|
|
162
|
+
|
|
163
|
+
return {
|
|
164
|
+
id: user.id,
|
|
165
|
+
username: user.username,
|
|
166
|
+
role: user.role,
|
|
167
|
+
};
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
export function getSessionCookieName(): string {
|
|
171
|
+
return SESSION_COOKIE_NAME;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
export function getSessionCookieMaxAge(): number {
|
|
175
|
+
return SESSION_TTL_SECONDS;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
export async function getAdminSessionFromRequest(
|
|
179
|
+
request: NextRequest,
|
|
180
|
+
): Promise<AdminSession | null> {
|
|
181
|
+
return authenticateSessionToken(
|
|
182
|
+
request.cookies.get(SESSION_COOKIE_NAME)?.value,
|
|
183
|
+
);
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
export async function getAdminSessionFromServerCookies(): Promise<AdminSession | null> {
|
|
187
|
+
const cookieStore = await cookies();
|
|
188
|
+
return authenticateSessionToken(cookieStore.get(SESSION_COOKIE_NAME)?.value);
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
export async function revokeAdminSessionFromRequest(
|
|
192
|
+
request: NextRequest,
|
|
193
|
+
): Promise<void> {
|
|
194
|
+
const token = request.cookies.get(SESSION_COOKIE_NAME)?.value;
|
|
195
|
+
if (!token?.startsWith("otas_")) {
|
|
196
|
+
return;
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
const { error } = await supabase
|
|
200
|
+
.from("ota_admin_sessions")
|
|
201
|
+
.update({ revoked_at: new Date().toISOString() })
|
|
202
|
+
.eq("token_hash", hashToken(token))
|
|
203
|
+
.execute();
|
|
204
|
+
|
|
205
|
+
if (error) {
|
|
206
|
+
throw new Error(`Failed to revoke admin session: ${error.message}`);
|
|
207
|
+
}
|
|
208
|
+
}
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
import { supabase } from "./supabase.js";
|
|
2
|
+
|
|
3
|
+
type EmbeddedUpdateRow = {
|
|
4
|
+
embedded_update_id: string;
|
|
5
|
+
created_at: string;
|
|
6
|
+
channel: string;
|
|
7
|
+
platform: "ios" | "android";
|
|
8
|
+
is_embedded: boolean;
|
|
9
|
+
inserted_at: string;
|
|
10
|
+
modified_at: string;
|
|
11
|
+
};
|
|
12
|
+
|
|
13
|
+
export type EmbeddedUpdateRecord = {
|
|
14
|
+
embeddedUpdateId: string;
|
|
15
|
+
createdAt: string;
|
|
16
|
+
channel: string;
|
|
17
|
+
platform: "ios" | "android";
|
|
18
|
+
isEmbedded: boolean;
|
|
19
|
+
insertedAt: string;
|
|
20
|
+
modifiedAt: string;
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
export type RegisterEmbeddedUpdateInput = {
|
|
24
|
+
embeddedUpdateId: string;
|
|
25
|
+
createdAt: string;
|
|
26
|
+
channel: string;
|
|
27
|
+
platform: "ios" | "android";
|
|
28
|
+
};
|
|
29
|
+
|
|
30
|
+
export class EmbeddedUpdateValidationError extends Error {}
|
|
31
|
+
|
|
32
|
+
const UUID_PATTERN =
|
|
33
|
+
/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
|
34
|
+
const CHANNEL_PATTERN = /^[a-z0-9][a-z0-9._-]{0,63}$/;
|
|
35
|
+
|
|
36
|
+
export function parseRegisterEmbeddedUpdateInput(
|
|
37
|
+
value: unknown,
|
|
38
|
+
): RegisterEmbeddedUpdateInput {
|
|
39
|
+
if (!value || typeof value !== "object") {
|
|
40
|
+
throw new EmbeddedUpdateValidationError("JSON body is required");
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
const input = value as Record<string, unknown>;
|
|
44
|
+
const embeddedUpdateId = String(
|
|
45
|
+
input.embeddedUpdateId || input.id || "",
|
|
46
|
+
).trim();
|
|
47
|
+
const createdAt = String(input.createdAt || "").trim();
|
|
48
|
+
const channel = String(input.channel || "").trim().toLowerCase();
|
|
49
|
+
const platform = String(input.platform || "").trim().toLowerCase();
|
|
50
|
+
|
|
51
|
+
if (!UUID_PATTERN.test(embeddedUpdateId)) {
|
|
52
|
+
throw new EmbeddedUpdateValidationError(
|
|
53
|
+
"embeddedUpdateId must be a valid UUID",
|
|
54
|
+
);
|
|
55
|
+
}
|
|
56
|
+
if (!createdAt || Number.isNaN(Date.parse(createdAt))) {
|
|
57
|
+
throw new EmbeddedUpdateValidationError(
|
|
58
|
+
"createdAt must be a valid ISO datetime",
|
|
59
|
+
);
|
|
60
|
+
}
|
|
61
|
+
if (!CHANNEL_PATTERN.test(channel)) {
|
|
62
|
+
throw new EmbeddedUpdateValidationError(
|
|
63
|
+
"channel must contain only lowercase letters, numbers, dots, underscores or hyphens",
|
|
64
|
+
);
|
|
65
|
+
}
|
|
66
|
+
if (platform !== "ios" && platform !== "android") {
|
|
67
|
+
throw new EmbeddedUpdateValidationError(
|
|
68
|
+
"platform must be ios or android",
|
|
69
|
+
);
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
return {
|
|
73
|
+
embeddedUpdateId,
|
|
74
|
+
createdAt: new Date(createdAt).toISOString(),
|
|
75
|
+
channel,
|
|
76
|
+
platform,
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export async function registerEmbeddedUpdate(
|
|
81
|
+
input: RegisterEmbeddedUpdateInput,
|
|
82
|
+
): Promise<EmbeddedUpdateRecord> {
|
|
83
|
+
const row = {
|
|
84
|
+
embedded_update_id: input.embeddedUpdateId,
|
|
85
|
+
created_at: input.createdAt,
|
|
86
|
+
channel: input.channel,
|
|
87
|
+
platform: input.platform,
|
|
88
|
+
is_embedded: true,
|
|
89
|
+
};
|
|
90
|
+
const { data, error } = await supabase
|
|
91
|
+
.from("ota_embedded_updates")
|
|
92
|
+
.upsert(row, { onConflict: "embedded_update_id" })
|
|
93
|
+
.select(
|
|
94
|
+
"embedded_update_id,created_at,channel,platform,is_embedded,inserted_at,modified_at",
|
|
95
|
+
)
|
|
96
|
+
.single();
|
|
97
|
+
|
|
98
|
+
if (error) {
|
|
99
|
+
throw new Error(`Failed to register embedded update: ${error.message}`);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const saved = data as EmbeddedUpdateRow;
|
|
103
|
+
return {
|
|
104
|
+
embeddedUpdateId: saved.embedded_update_id,
|
|
105
|
+
createdAt: saved.created_at,
|
|
106
|
+
channel: saved.channel,
|
|
107
|
+
platform: saved.platform,
|
|
108
|
+
isEmbedded: saved.is_embedded,
|
|
109
|
+
insertedAt: saved.inserted_at,
|
|
110
|
+
modifiedAt: saved.modified_at,
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export async function listEmbeddedUpdates(): Promise<EmbeddedUpdateRecord[]> {
|
|
115
|
+
const { data, error } = await supabase
|
|
116
|
+
.from("ota_embedded_updates")
|
|
117
|
+
.select(
|
|
118
|
+
"embedded_update_id,created_at,channel,platform,is_embedded,inserted_at,modified_at",
|
|
119
|
+
)
|
|
120
|
+
.order("created_at", { ascending: false })
|
|
121
|
+
.execute();
|
|
122
|
+
|
|
123
|
+
if (error) {
|
|
124
|
+
throw new Error(`Failed to fetch embedded updates: ${error.message}`);
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
return ((data || []) as EmbeddedUpdateRow[]).map((row) => ({
|
|
128
|
+
embeddedUpdateId: row.embedded_update_id,
|
|
129
|
+
createdAt: row.created_at,
|
|
130
|
+
channel: row.channel,
|
|
131
|
+
platform: row.platform,
|
|
132
|
+
isEmbedded: row.is_embedded,
|
|
133
|
+
insertedAt: row.inserted_at,
|
|
134
|
+
modifiedAt: row.modified_at,
|
|
135
|
+
}));
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export async function deleteEmbeddedUpdateById(embeddedUpdateId: string) {
|
|
139
|
+
const { error } = await supabase
|
|
140
|
+
.from("ota_embedded_updates")
|
|
141
|
+
.delete()
|
|
142
|
+
.eq("embedded_update_id", embeddedUpdateId)
|
|
143
|
+
.execute();
|
|
144
|
+
|
|
145
|
+
if (error) {
|
|
146
|
+
throw new Error(`Failed to delete embedded update: ${error.message}`);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
return { deletedId: embeddedUpdateId };
|
|
150
|
+
}
|